【发布时间】:2019-04-20 17:20:49
【问题描述】:
我的应用使用
- axios 从后端服务器获取用户信息
- vuex 存储用户
- vue-router 在每个用户的页面上导航
在 App.vue 中,fetch 被调度
export default {
name: 'app',
components: {
nav00
},
beforeCreate() {
this.$store.dispatch('fetchUsers')
}
}
在 store.js 中,users 是一个带有pk(主键)的对象。
export default new Vuex.Store({
state: {
users: {},
},
getters: {
userCount: state => {
return Object.keys(state.users).length
}
},
mutations: {
SET_USERS(state, users) {
// users should be backend response
console.log(users.length)
users.forEach(u => state.users[u.pk] = u)
actions: {
fetchUsers({commit}) {
Backend.getUsers()
.then(response => {
commit('SET_USERS', response.data)
})
.catch(error => {
console.log("Cannot fetch users: ", error.response)
})
})
这里Backend.getUsers()是一个axios调用。
在另一个映射到vue-router 中的/about 的组件中,它只是通过getter 显示userCount。
现在应用的行为取决于时间。如果我先访问/ 并等待2-3 秒,然后转到/about,userCount 会正确显示。但是,如果我直接访问/about,或者先访问/,然后快速导航到/about,userCount 就是0。但在控制台中,它仍然显示正确的用户数(来自SET_USERS 的登录)。
我在这里错过了什么?商店 getter 不应该在 users 中看到更新并再次渲染 HTML 显示吗?
【问题讨论】:
标签: vue.js vuex vue-router