【问题标题】:Vuex: How to subscribe to event from actionVuex:如何从动作订阅事件
【发布时间】:2019-12-02 23:46:24
【问题描述】:

我是 Vuex 的新手,我想做这件事很简单,但我不知道典型的 Vuex 代码使用的最佳模式是什么。

我有一个初始化和存储Machine 对象的操作,该对象还可以发出我想订阅的状态事件并获得商店用户的通知。

例如:此操作由 :

定义
createMachine({ commit, state }) {
      return state.m.createMachine().then(
        function (machineObject) {
          commit('setMachine', machineObject);
         }
      )
    }

我想从 store 中监听创建的 machineObject 对象事件,并最终更新一个我可以从组件中观察到的 store 变量,方法是:

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

我说清楚了吗?

谢谢。

【问题讨论】:

    标签: events vuex store


    【解决方案1】:

    Vuex 有 subscribeAction 方法, 见vuex.subscribeAction

    store.subscribeAction((action, state) => {
        console.log(action.type);
        console.log(action.payload);
    
        if (action.type === 'createMachine') {
            // do what you want there
        }
    });
    

    【讨论】:

    • Action.type 总是显示 vuex store 的动作名称?
    猜你喜欢
    • 1970-01-01
    • 2013-11-03
    • 2010-09-07
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多