Vuex:如何从商店更新组件数据或调用组件方法

时间:2019-09-10 17:17:33

标签: vue.js vue-component vuex

如果我有商店:

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)
    }
  }
}

我有一个组件,其引用为'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()吗?

1 个答案:

答案 0 :(得分:0)

您可以使用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