【问题标题】:Vuex: How to update component data or call component methods from StoreVuex:如何更新组件数据或从 Store 调用组件方法
【发布时间】:2020-01-12 11:49:44
【问题描述】:

如果我有商店:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    foo: bar
  },
  mutations: {
    updateComponent (state) {
      // computation and logic
      // update state
      this.$refs.myComponent.updateComponent(state.foo)
    }
  }
}

我有一个带有 ref 'myComponent' 的组件:

<template>
  ...
</template>
<script>
  export default {
    ...
    methods: {
      updateComponent(payload) {
        // do stuff
      }
    }
  }
</script>

我想从商店调用“updateComponent()”方法。我可以在其他视图和组件中使用this.$refs.myComponent,但它在商店中不起作用。我收到错误TypeError: Cannot read property 'myComponent' of undefined

从商店使用时,this 显然不是 this.$refs.myComponent 的正确范围。

我可以从我的存储突变中调用updateComponent(),以及如何调用?

【问题讨论】:

  • 我不明白调用 store 的目的是什么,如果它不操纵 store 状态,为什么不直接在本地更新组件?
  • @jacob13smith 在真实场景中,mutation 中会进行大量计算,然后更新状态,然后组件需要根据状态更新自身。我可以通过另一种方式解决这个问题,例如观察者,但想知道这是否可能?
  • 你也可以使用Subscribe to store mutations
  • 您可以在 computed 中创建一个 getter 或只是 this.$store.state.something。这不就是你要找的吗? vuex.vuejs.org/guide/state.html

标签: vue.js vue-component vuex


【解决方案1】:

您可以使用vuex 的订阅方法。在已安装阶段订阅您的组件:

mounted() {
    this.$store.subscribe((mutation, state) => {
        switch(mutation.type) {
          case 'updateComponent':
            // Update your component with new state data
          break;
        } 
     })
  }

参考:https://vuex.vuejs.org/api/#subscribe

【讨论】:

  • 谢谢。这应该可以解决问题。我会尝试并标记为正确。但是有一个问题:为什么要使用 switch 语句?这是为了管理订阅多个突变的可能性吗?
  • 是的,subscribe 方法会在每个突变上触发,如果您只想订阅一个突变,您可以使用 if 语句。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2018-09-09
  • 2017-01-10
  • 1970-01-01
  • 2022-08-12
  • 2019-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多