【问题标题】:vuex getter does not update on another component depending on timingvuex getter 不会根据时间在另一个组件上更新
【发布时间】: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


    【解决方案1】:

    由于它是一个对象,因此 Vue 无法检测到属性的变化,而且它对计算属性的反应更小。

    复制自https://vuex.vuejs.org/guide/mutations.html:

    向对象添加新属性时,您应该:

    Use Vue.set(obj, 'newProp', 123),或

    用一个新的对象替换那个对象。例如,使用对象扩展语法我们可以这样写:

    state.obj = { ...state.obj, newProp: 123 }
    

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 2017-12-07
      • 1970-01-01
      • 2017-12-08
      • 2021-01-18
      • 2017-04-13
      • 2018-02-22
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多