vue.js - 如何使用 Vue/Vuex 正确排序调用
问题描述
我在下面有一些骨架代码,它演示了我在强制调用正确顺序时遇到的问题。我想要的顺序是:
- 用户触发 Foo.vue 的 someLocalMethod()。
- 设置了一个标志,以便 Bar 会意识到已经进行了更改。
- 该标志将触发 Bar.vues 的观察者继续进行一些工作。
- 工作完成后,它将取消设置标志
- Foo.vue 的 someLocalMethod() 将意识到该标志未设置并继续其工作
我应该提到 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');
}
},
解决方案
简单的解决方案
问题Foo.vue
本质上是尝试运行可能最容易使用事件总线的doWorkRelevantToBarPage
方法,如另一个响应中建议的那样,但是如果您想使用 vue.js 创建更大/可扩展的应用程序,则使用事件总线不是一个好主意Bar.vue
问题在于方法
我doWorkRelevantToBarPage
假设您很可能想要更改存储在其中的某些状态Bar.vue
或运行其他一些这样做的方法。现在您有了想要运行它的方法,Foo.vue
但这似乎是错误的方法(尤其是如果您想使用 vuex),您会发现您实际上是在尝试从外部更改组件的状态,这通常不是一个好的主意。
使用 Vuex
以下步骤将总结您可以做些什么来调整您的代码以使用 vuex
- 将
Foo.vue
需要从外部更改的任何状态移动到商店。 - 为您放置在商店中的状态创建突变和吸气剂
- 将 getter 连接到您的
Bar.vue
组件 - 创建一个提交必要突变的操作,如下所示(选择更具描述性的名称):
updateBarData({commit, dispatch}, ...args) {
commit('mutation1')
commit('mutation2')
commit('mutation3')
dispatch('action1')
dispatch('action2')
// ... other logic
}
- 将动作添加到
Foo.vue
methods: {
...mapActions('store', ['someStoreCall', 'updateBarData']),
someLocalMethod(someData) {
this.updateBarData()
this.someStoreCall(someData)
}
}
我希望这有帮助。
推荐阅读
- c++ - 在单词搜索中获取 TLE
- sql - SQL Server:如何根据查询返回的列更新表?
- session - 在 Coldfusion 中更改密码时如何注销其他会话
- tensorflow - IndexError:使用 np.argmax 函数时列表索引超出范围
- reactjs - 没有模块的 Typescript 和 React - 找不到名称“React”
- node.js - 用 mongoose 中的 id 数组更新嵌套数组
- swift - VLCKit:当我停止视频时,无法将 VLCMediaPlayer.position 重置为 0
- java - 甚至未列出的所有内容都在使用 recyclerView 滚动
- java - 如何根据每行的分数对矩阵进行排名?
- powershell - 为什么我收到警告“变量 'lastUpdate' 已分配但从未使用过。” 在这个 PowerShell