我有一个add-user.vue
的部件.这是我添加新用户和编辑现有用户的模板.所以在页面加载时,我判断路由是否有id
,如果有,我从状态数组中加载一个用户来编辑它.我的问题是user
是未定义的,因为状态数组users
是空的.如何确保我的用户对象没有未定义.它有时会加载,但刷新时不会.我以为我已经覆盖了它,但没有.这是我的设置.我错过了什么?
store
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
个用户
<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];
});
}
}
}