【问题标题】:Vuex returning some data back the the componentVuex 向组件返回一些数据
【发布时间】:2019-06-10 11:51:32
【问题描述】:

我的 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.js promise axios vuex


    【解决方案1】:

    您已发送操作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 将状态传递给其他组件)。

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

    【讨论】:

    • 谢谢,这就是我在其他地方的做法,这似乎是一种“另类”的方式!我虽然可以在不检查 $store.state 的情况下完成它。
    • 是的,您是正确的,您可以从 axios fetch 方法中删除 store 的实例 - 所以这是您在利用 Vuex store 时需要做出的权衡(通过操作或可重用方法将方法隔离在组件中)
    • 在我的例子中,该组件可能存在两次(常规,有时在模态 div 中)。两个组件必须具有不同的状态,可以通过分派的函数返回值进行修改。因此,一种值状态将不起作用,因为在这种情况下,两个组件的值在 $store.state 中将是相同的。我该如何解决这个问题?
    • 你问过这个问题么@Dong3000
    • @DenisTsoi 我在这里具体化了:stackoverflow.com/questions/64842269/…
    猜你喜欢
    • 2021-09-30
    • 2021-03-08
    • 2020-12-11
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多