确保渲染组件之前已加载Vuex状态

时间:2018-08-13 08:17:13

标签: vue.js vue-component vuex

我有一个add-user.vue组件。这是我用于添加新用户和编辑现有用户的模板。因此,在页面加载时,我检查route是否具有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组件中,我在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];
                });
            }
  }
}

3 个答案:

答案 0 :(得分:4)

尽管这解决了,但我会为将来的来者作答。您可以按照Shu的建议事先发出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>

答案 1 :(得分:2)

我将在beforeRouteEnter中使用User.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在组件初始化之前不可用。

答案 2 :(得分:1)

对于这种特殊情况,它只是来回到同一vue实例。通过添加// A process that stores something in a Postgres instance. const processA: Process = new Process(new PostgresStorage()); // A process that stores something on the filesystem. const processB: Process = new Process(new FilesystemStorage()); 来解决它,所以看起来像这样。

:key="some-unique-key"
相关问题