VueX等待执行突变

问题描述 投票:0回答:1

是否可以在VueX中的方法中,在 mounted() 等到其他组件中的某个突变被执行?

因为有时那个突变是在之前执行的,有时是在之后执行的,所以我想知道当组件被挂载时,是否可以在它运行之后等待。

  mounted() {
    // await MutationName
    this.columnItemsInit();
  }
vue.js vuejs2 vuex vuex-modules
1个回答
2
投票

你可以用 储存.订阅 办法

mounted() {
  let unsubscribe = null
  unsubscribe = this.$store.subscribe(({ type }) => {
    if (type === 'MutationName') {
      this.columnItemsInit()
      unsubscribe() // So it only reacts once.
    }
  })
}

0
投票

除非组件之间有某种关联(父到子),否则会很棘手。你可以在你的最终组件中的计算属性中添加一个观察者,观察存储空间中的一个值(例如命名为 "alpha"),这个值可以在第一个组件完成它的功能后更新。

组件1

mounted() {
    // Run function then update state value "alpha" in store to say I am complete
}

构成部分2

computed {
    valueInStore() {
        // return state value "alpha"
    }
},

watch: {
    valueInStore(value) {
        // If value "alpha" is complete run the following code
        this.columnItemsInit();
    }
}

0
投票

正确的做法是使用vuex的action.action的本质是异步的,所以当你执行一个action的时候,你可以为action的发生设置一个wait。

正如 文件

动作与突变类似,区别在于。

  • 行动不是突变状态,而是提交突变。
  • Actions可以包含任意的异步操作,所以你可以等待该操作被执行后再传给下一个操作。

所以你可以等待该操作被执行后再传给下一个操作。

举个例子。

const store = new Vuex.Store({
    state: {
        token: null
    },
    mutations: {
        SET_TOKEN (state, payload) {
          state.token = payload
        }
      },
      actions: {
        SET_TOKEN ({ context }, token) {
          context.commit('SET_TOKEN', token)
        }
      }
})

然后在你的methodshooks中通过dispatch方法调用一个action。

methods: {
    async refreshStoreValue() {
        await this.$store.dispatch('SET_TOKEN', token) //this will call an action declared in your store.
    }
}

你可以在一个异步的方法声明里面使用该语句,或者在你的生命周期钩子里面(创建、挂载等)。

© www.soinside.com 2019 - 2024. All rights reserved.