Computed 属性 依赖于 vuex store。如何更新缓存值?

Computed property depends on vuex store. How to update the cached value?

this.$store.state.Auth.loginToken 的值被其子组件之一修改。 this.$store.state.Auth.loginToken的初始值为undefined。但是,其值的更新仍然对 navItems 的缓存值没有影响,因此它总是 returns 第二个值。

computed: {
    navItems () {
        return this.$store.state.Auth.loginToken != undefined ?
        this.items.concat([
            { icon: 'add', title: 'Add new journal entry', to: '/' },
            { icon: 'power_settings_new', title: 'Logout', to: '/logout'}
        ]) :
        this.items.concat([
            { icon: 'play_arrow', title: 'Login', to: '/login' }
        ])
    }
}

有没有更好的方法来监视 this.$store.state.Auth.loginToken 以便它可以像 navItems 一样使用?

我创建了一个基本示例来说明如何使用 vuex getter 和 Auth 令牌 (codepen):

const mapGetters = Vuex.mapGetters;

var store = new Vuex.Store({
  state: {
    Auth: {
      loginToken: ''
    },
    menuItems: [
       { icon: 'home', title: 'Home', to: '/' },
       { icon: 'about', title: 'About', to: '/about' },
       { icon: 'contact', title: 'Contact', to: '/contact' }
    ]
  },
  mutations: {
    SET_LOGIN_TOKEN(state, data) {
      state.Auth.loginToken = 1
    }
  },
  getters: {
    menuItems(state, getters) {
      if(state.Auth.loginToken !== '') {
        return state.menuItems.concat([{
            icon: 'profile', title: 'Profile', to: '/profile'
        }])
      }
      return state.menuItems
    },
    loggedIn(state) {
      return state.Auth.loginToken !== ''
    }
  },
  actions: {
    doLogin({commit}) {
       commit('SET_LOGIN_TOKEN', 1)
    }
  }
});

new Vue({
  el: '#app',
  store,
  data: function() {
    return {
      newTodoText: "",
      doneFilter: false
    }
  },
  methods: {
    login() {
       this.$store.dispatch('doLogin')
    }
  },
  computed: {
   ...mapGetters(['menuItems', 'loggedIn'])
  }
})

这只是一个示例,因此您可以忽略实际的登录操作。另外,store 应该是一个目录,getters,mutations 和 actions 应该有自己的文件,然后导入到 store 的 index.js 中,就像这样 example