我在下面有一些框架代码,它们演示了我在强制执行正确的调用顺序时遇到的问题。我想要的顺序是:
- 用户触发 Foo.vue 的 someLocalMethod()。
- 设置了一个标志,这样 Bar 就会知道已经进行了更改。
- 标志将触发 Bar.vues 的观察者继续做一些工作。
- 工作完成后,它将取消设置标志
- Foo.vue 的 someLocalMethod() 将意识到标志未设置并继续其工作
我应该提到,Bar 和 Foo 都在做改变存储的工作,因此文件是相关的(而不是单独使用存储作为两个文件之间的标志)。
我假设有更好/更清晰的方法来处理我正在做的事情,但我不能完全确定。代码如下所示。
条形图
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);
}
},
商店.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');
}
},
最佳答案
对于这个用例,我建议使用事件总线:
- 在您的 Foo 组件的
LocalMethod
中,您在总线上发出一个事件(例如称为“FooChanged”) - Bar 组件中的事件处理程序(订阅“FooChanged”事件)将完成其工作,然后发出另一个事件(例如称为“BarFinished") 在公交车上
- Foo 组件中的事件处理程序(订阅了“BarFinished”事件)将继续您流程中的下一步
像这样:
事件总线
import Vue from "vue";
export default new Vue();
Foo.vue
import events from "eventBus";
export default
{
created()
{
events.$on("BarFinished", this.onBarFinished);
},
beforeDestroy()
{
events.$off("BarFinished", this.onBarFinished);
},
methods:
{
LocalMethod()
{
....
events.$emit("FooChanged", param1, param2);
},
onBarFinished(param1)
{
...
}
}
}
条形图
import events from "eventBus";
export default
{
created()
{
events.$on("FooChanged", this.onFooChanged);
},
beforeDestroy()
{
events.$off("FooChanged", this.onFooChanged);
},
methods:
{
onFooChanged(param1, param2)
{
...
events.$emit("BarFinished", param1);
}
}
}
关于vue.js - 如何使用 Vue/Vuex 正确排序调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59990111/