首页 > 解决方案 > Vuex 向组件返回一些数据

问题描述

我的 vuex 操作中有一个 axios 调用

  return axios({
      method: 'get',
      url: `/myurl`,

    }).then(function (response) {
      context.commit('value', response.data.data);
    }),

但是,这是在我的组件中调用的

this.$store.dispatch("fetchmystuff")

如何向组件返回值?

过去我已将 then() 附加到调度

 this.$store.dispatch("fetchmystuff")
    .then(function (response) {
     //do some component stuff
 }),

但我想先在 vuex 中运行提交,然后向组件返回一些东西。

标签: vue.jspromiseaxiosvuex

解决方案


你已经发送了 action fetchmystuff。在您的组件中,您将需要其中任何一个。

1.查询商店的状态value

computed: {   
  value() {    
    return this.$store.state.value
  } 
}

2. 调用value从计算属性中获取状态的 getter

在组件中

computed: {   
  value() {    
    return this.$store.getters.value
  } 
}

在商店 getters.js

getters: {
  // ...
  value: (state, getters) => {
    return getters.value
  }
}

调度程序/操作不需要访问组件
(因为状态仅通过突变/提交设置在存储中,并通过 getter 将状态传递给其他组件)。

这允许在商店和应用程序的组件之间解耦关注点。


推荐阅读