【问题标题】:How to pass data to component after action dispatched to Vuex?动作发送到 Vuex 后如何将数据传递给组件?
【发布时间】:2020-12-10 00:38:21
【问题描述】:

我正在使用 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")
    }
});

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

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

///component.js

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

因此,一方面它似乎在调度操作,但是当我尝试从状态访问单个对象时,它会自行处理。我尝试访问该州内对象的方式有问题吗?

【问题讨论】:

  • 您想在检索到数据之前“阻止”任何渲染吗?如果没有,我认为@ilya-salmasov 的回答会奏效。

标签: vue.js vue-component vuex flux


【解决方案1】:

您需要“等待”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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-15
    • 2019-06-14
    • 2018-10-04
    • 2021-04-23
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2021-10-13
    相关资源
    最近更新 更多