Vue 监听 Vuex 提交? [英] Vue listen for Vuex commit?
问题描述
有没有办法在不查看随提交更改的任何属性的情况下监听 Vuex 提交?只是简单地找出是否发生了提交?
Is there a way to listen to a Vuex commit without watching any of the properties that are changed with the commit? Just simply finding out if a commit has happened?
我有一个过滤器组件,我想将其放入 NPM 包中,但我已经有一个用例,我想设置一个 cookie,在选择过滤器时存储过滤器首选项.
I have a Filter component that I want to put into a NPM package but I already have a use case where I would want to set a cookie storing the filter preferences whenever a filter is selected.
显然,设置 cookie 等不是过滤器组件的责任,这应该是可选的.
Obviously it is not the responsibility of the filter component to set cookies etc. and this is something that should be optional.
我想一种方法是使用全局事件总线,但这意味着使用我的包的用户必须完全按照我的需要设置一个.每当过滤器事件被触发时,用户就可以执行必要的操作.
I guess one way would be to use a global event bus but this would mean a user which uses my package would have to set one up exactly how I need it. Whenever the filter event gets fired a user could then perform necessary actions.
如何将这个 SRP
保持为 NPM 包并保持干净,同时仍允许用户挂钩某些事件?
How do I keep this SRP
and clean as an NPM package while still allowing a user to hook into certain events?
这是一个广泛的问题,但我希望你能明白要点.
Kind of a broad question but I hope you get the gist.
推荐答案
您可以使用商店的 subscribe
方法监听提交/变更.
You can listen for commits/mutations using the store's subscribe
method.
API 参考:https://vuex.vuejs.org/en/api.html
Vuex 插件也适用于这个确切的用例.文档:https://vuex.vuejs.org/en/plugins.html
Vuex plugins exist for this exact use case as well. Docs: https://vuex.vuejs.org/en/plugins.html
示例:
let vuexPlugin = (store) => {
let whitelist = ['abc', 'def', 'ghi'];
store.subscribe((mutation, state) => {
if (whitelist.includes(mutation.type)) {
// your code here
}
});
};
这篇关于Vue 监听 Vuex 提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!