在将动作分派给Vuex之后如何将数据传递到组件?

问题描述

我正在使用Vuex尝试管理应用程序级数据。我使用axios提取数据,然后将该数据传播到组件中的数据变量。没什么复杂的。

我的商店看起来像这样

// store.js
// appropriate imports and such

export const store = new Vuex.Store({
    state: {
      var: []
    },actions:{
      getData(context){
        axios.get('/endpoint').then(function(response){
          context.state.var = res.data.value1;
          console.log("action in store.js run");

//appropriate brackets,etc below

然后我在app.js中调度此动作

//appropriate imports and such above

const app = new Vue({
    el: '#app',store: store,created() {
      this.$store.dispatch('getRightSidebar')
      console.log("action dispatched")
    }
});

我使用创建的生命周期挂钩来确保在安装组件之前 调度此操作。当然,这时两条消息应记录到控制台。一条消息来自创建的生活方式挂钩,另一条消息来自实际派遣的动作。但是,当我运行该应用程序时,只会记录以前的消息。当然,当操作消失时,实际的方法/请求会被调用/执行。

现在,当我从组件的已安装生命周期挂钩中打印状态变量的值时,它们是未定义的。但是,如果我打印状态,它将使用适当的数据记录对象

///component.js

mounted() {
  console.log("component mounted")
  console.log(this.$store.state.var) // undefined
  console.log(this.$store.state) // Obeject with the appropriate data
}

因此,一方面,它似乎调度了操作,但是当我尝试从状态访问单个对象时,它就会崩溃。我尝试访问状态内对象的方式有问题吗?

解决方法

您需要“等待” getData的诺言

当created()挂钩运行时,没有数据

export const store = new Vuex.Store({
    state: {
      var: []
    },actions:{
       getRightSidebar(context){
        // must return Promise to subscribe to it!
        return axios.get('/endpoint').then(function(response){
          context.state.var = res.data.value1;
          console.log("action in store.js run");
const app = new Vue({
    el: '#app',store: store,data: {
      isLoading: true
    },async mounted() {
      await this.$store.dispatch('getRightSidebar')
      // after this there is gonna be some data 
      this.isLoading = false
    }
})
<template>
  <div>
    <div v-if='isLoading'>loading...</div>
    <div v-else>{{$store.state.yourvariable}}</div>
 </div>
</template>