首页 > 解决方案 > 如何使用 Vue/Vuex 正确排序调用

问题描述

我在下面有一些骨架代码,它演示了我在强制调用正确顺序时遇到的问题。我想要的顺序是:

我应该提到 Bar 和 Foo 都在做改变存储的工作,所以文件是相关的(而不是仅仅使用存储作为两个文件之间的标志)。

我假设有一种更好/更清洁的方法来处理我正在做的事情,但我不能完全理解它。代码如下所示。

酒吧.vue

computed: {
  ...mapGetters('store', ['getSomeFlag']),
},
methods: {
  ...mapMutations('store', ['setSomeFlag']),
},
watch: {
  getSomeFlag(newValue) {
    if (newValue === true) {
      console.log('Flag is set. Going to do work');
      doWorkRelevantToBarPage();
      setSomeFlag(false);
    }
  }
}

Foo.vue

methods: {
  ...mapActions('store', ['someStoreCall']),
  ...mapMutations('store', ['setSomeFlag']),

  someLocalMethod(someData) {
    this.setSomeFlag(true);
    // somehow wait until Bar.vue's watcher becomes aware of it and completes it's own work
    this.someStoreCall(someData);      
  }
},

store.js

state: {
  someFlag: false,
  data: { 
    // Can be tons of nested structures, properties, etc
  },
},
getters: {
  getSomeFlag: (state) => state.someFlag,
},
mutations: {
  setSomeFlag(state, value) {
    state.someFlag = value;
  },
},
actions: {
  async someStoreCall({dispatch, commit, state}, data) {
    console.log('In someStoreCall');
  }
},

标签: vue.jsvuex

解决方案


简单的解决方案

问题Foo.vue本质上是尝试运行可能最容易使用事件总线的doWorkRelevantToBarPage方法,如另一个响应中建议的那样,但是如果您想使用 vue.js 创建更大/可扩展的应用程序,则使用事件总线不是一个好主意Bar.vue

问题在于方法

doWorkRelevantToBarPage假设您很可能想要更改存储在其中的某些状态Bar.vue或运行其他一些这样做的方法。现在您有了想要运行它的方法,Foo.vue但这似乎是错误的方法(尤其是如果您想使用 vuex),您会发现您实际上是在尝试从外部更改组件的状态,这通常不是一个好的主意。

使用 Vuex

以下步骤将总结您可以做些什么来调整您的代码以使用 vuex

  1. Foo.vue需要从外部更改的任何状态移动到商店。
  2. 为您放置在商店中的状态创建突变和吸气剂
  3. 将 getter 连接到您的Bar.vue组件
  4. 创建一个提交必要突变的操作,如下所示(选择更具描述性的名称):
updateBarData({commit, dispatch}, ...args) {
  commit('mutation1')
  commit('mutation2')
  commit('mutation3')
  dispatch('action1')
  dispatch('action2')
  // ... other logic
}
  1. 将动作添加到Foo.vue
methods: {
  ...mapActions('store', ['someStoreCall', 'updateBarData']),
  someLocalMethod(someData) {
    this.updateBarData()
    this.someStoreCall(someData)
  }
}

我希望这有帮助。


推荐阅读