IT이야기

구성 요소를 렌더링하기 전에 Vuex 상태가 로드되었는지 확인하십시오.

cyworld 2022. 4. 13. 21:30
반응형

구성 요소를 렌더링하기 전에 Vuex 상태가 로드되었는지 확인하십시오.

나는 a를 가지고 있다.add-user.vue구성 요소새 사용자를 추가하고 기존 사용자를 편집하기 위한 나의 템플릿이다.페이지 로드에서 경로에 다음이 있는지 확인하십시오.id, 그렇다면 편집하기 위해 상태 배열에서 사용자를 로드한다.내 문제는 이다.user상태 배열로 인해 정의되지 않음users비어 있다.사용자 개체가 정의되지 않았는지 확인하는 방법그것은 가끔 로딩되지만 새로 고치면 로딩하지 않는다.나는 내가 그것을 덮은 줄 알았는데 아니었어.이건 내 설정이야내가 뭘 놓쳤지?

저장하다

state: {
  users: []
},

getters: {
  users: state =>
    _.keyBy(state.users.filter(user => user.deleted === false), 'id')
},

actions: {
  fetchUsers({
    commit
  }) {
    axios
      .get('http://localhost:3000/users')
      .then(response => {
        commit('setUsers', response.data);
      })
      .catch(error => {
        console.log('error:', error);
      });
  }
}

나의add-user.vue구성 요소: I have nothing in the weathers.data() computed:{}그리고created()

data() {
  return {
    user: {
      id: undefined,
      name: undefined,
      gender: undefined
    }
  };
},

computed: {
  ...mapGetters(['users'])
},

created() {
  if (this.$route.params.userId === undefined) {
    this.user.id = uuid();
    ...
  } else {
    this.user = this.users[this.$route.params.userId];
  }
}

템플릿

<template>
  <div class="add-user" v-if="user"></div>
</template>

나의User.vue다음 설정이 있으며, 여기서 사용자 가져오기를 초기화한다.created()

<template>
  <main class="main">
    <AddUser/>
    <UserList/>
  </main>
</template>

<script>
import AddUser from '@/components/add-user.vue';
import UserList from '@/components/user-list.vue';

export default {
    name: 'User',

    components: {
        AddUser,
        UserList
    },

    created() {
        this.$store.dispatch('fetchUsers');
    }
};
</script>

나는 이것을 시도해 보았다.내 편집기에 저장할 때는 작동하지만 새로 고침에는 작동하지 않는다.dispatch().then()앞장을 서서 달리다mutation사용자가 설정한다.

created() {
  if (this.$route.params.userId === undefined) {
    this.user.id = uuid();
    ...
  } else {
    if (this.users.length > 0) {
                this.user = this.users[this.$route.params.userId];
            } else {
                this.$store.dispatch('fetchUsers').then(() => {
                    this.user = this.users[this.$route.params.userId];
                });
            }
  }
}

나는 할 것이다beforeRouteEnterUser.vue데이터가 로드되기 전에 구성 요소가 초기화되지 않도록 하십시오.(사용한다고 가정할 때)vue-router)

beforeRouteEnter (to, from, next) {
    if (store.state.users.length === 0) {
        store.dispatch(fetchUsers)
        .then(next);
    }
},

그래야 할 것이다.import store from 'path/to/your/store'때문에this.$store구성 요소를 초기화할 때까지 사용할 수 없음.

비록 이것이 해결되었지만, 나는 미래의 손님들을 위해 대답할 것이다.발행 가능dispatch슈가 제안한 대로 사전에, 그렇지 않으면 당신은 여전히 같은 부품으로 파견할 수 있다.mounted후크를 사용하되 일부 상태 변수를 사용하여 진행률을 추적하십시오.

data:{
    ...
    loading:false,
    ...
},
...
mounted(){
this.loading = true,
this.$store
  .dispatch('fetchUsers')
  .finally(() => (this.loading=false));
}

그런 다음 템플릿에서 다음을 사용하십시오.loading페이지를 렌더링하거나 일부 스핀너 또는 진행 표시줄을 렌더링하는 상태 변수:

<template>
    <div class='main' v-if="!loading">
        ...all old template goes her
    </div>
    <div class="overlay" v-else>
        Loading...
    </div>
</template>

<style scoped>
    .overlay {
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 10;
      color: #FFFFFF;
    }
</style>

이 특별한 경우에 그것은 단지 같은 vue를 왔다 갔다 하고 있었다.덧셈으로 해결:key="some-unique-key"이렇게 생겼어.

<template>
  <main class="main">

    <AddUser :key="$route.params.userId"/>

    <UserList/>

  </main>
</template>

참조URL: https://stackoverflow.com/questions/51817967/ensure-that-vuex-state-is-loaded-before-render-component

반응형