VueJS - 访问已安装的商店数据

Pho*_*rce 3 vue.js vuejs2

我无法理解以下内容:

我有一个store包含应用程序所需的变量.特别是,有一个globalCompanies商店:

globalCompanies: {
   current: [],
   all: [],
   currentName: "",
}
Run Code Online (Sandbox Code Playgroud)

在另一个组件中,我想要执行以下操作:

mounted() {
   this.$store.dispatch( "fetchUsers" );

   var currentName = this.$store.state.globalCompanies.currentName; 

   console.log(currentName); 
},
Run Code Online (Sandbox Code Playgroud)

但是,这只是显示为空.我知道值是存在的,因为我有computed返回它currentName并且它在视图本身内工作正常.它只是不喜欢它在安装组件中的事实.

我哪里出错了,我该怎么做才能解决这个问题?我真的需要捕获公司名称,以便将它用于一些实时事件.

Ego*_*kio 5

作为我们讨论的结果:

在组件mounted钩子中访问的Vuex状态值问题中,返回空值,因为它是在mounted执行前未解析的异步操作中设置的.

当Vuex中的异步操作使用某个值解析时需要触发某些函数时,可以使用watch计算属性来实现它,该属性从Vuex状态返回一个值.当存储中的值更改时,计算属性将反映这些更改并且watch侦听器将执行:

const store = new Vuex.Store({
  state: {
    globalCompanies: {
      test: null
    }
  },
  mutations: {
    setMe: (state, payload) => {
      state.globalCompanies.test = payload
    }
  },
  actions: {
    pretendFetch: ({commit}) => {
      setTimeout(() => {
        commit('setMe', 'My text is here!')
      }, 300)
    }
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    cp: function() { // computed property will be updated when async call resolves
      return this.$store.state.globalCompanies.test;
    }
  },
  watch: { // watch changes here
    cp: function(newValue, oldValue) {
      // apply your logic here, e.g. invoke your listener function
      console.log('was: ', oldValue, ' now: ', newValue)
    }
  },
  mounted() {
    this.$store.dispatch('pretendFetch');
    // console.log(this.cp, this.$store.state.globalCompanies.test); // null
    // var cn = this.$store.state.globalCompanies.test; // null
    // console.log(cn) // null
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<script src="https://unpkg.com/vuex@2.3.1"></script>
<div id="app">
  {{ cp }}
</div>
Run Code Online (Sandbox Code Playgroud)