问题描述
我有一个 add-user.vue
组件.这是我添加新用户和编辑现有用户的模板.因此,在页面加载时,我检查路由是否具有 id
,如果是,则从状态数组加载用户以对其进行编辑.我的问题是 user
未定义,因为状态数组 users
为空.如何确保我的用户对象不是未定义的.它有时会加载,但在刷新时不会加载.我以为我把它盖好了,但没有.这是我的设置.我在这里错过了什么?
I have a add-user.vue
component. It is my template for adding a new user and editing a existing user. So on page load I check if route has a id
, if so I load a user from a state array to edit it. My issue is that user
is undefined because the state array users
is empty. How can I ensure that my user object isn't undefined. It does load sometimes but on refresh it doesn't. I thought I had it covered but nope. This is my setup. What am I missing here?
商店
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 中有以下内容()
In my add-user.vue
component I have the following in the data()
computed:{}
and 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()
My User.vue
I have the following setup, where I init the fetch of users on 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
之前运行.
I have tried this. When saving in my editor it works but not on refresh. The dispatch().then()
run before the mutation
setting the users does.
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];
});
}
}
}
推荐答案
对于这个特殊情况,它只是来回切换到同一个 vue 实例.通过添加 :key="some-unique-key"
解决了它,所以它看起来像这样.
For this particular case it was just going back and forth to the same vue instance. Solved it by adding :key="some-unique-key"
, so it looks like this.
<template>
<main class="main">
<AddUser :key="$route.params.userId"/>
<UserList/>
</main>
</template>
这篇关于确保在渲染组件之前加载 Vuex 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!