Vue listen for Vuex commit?

荒凉一梦 提交于 2019-12-10 10:00:56

问题


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?

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.

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.

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.


回答1:


You can listen for commits/mutations using the store's subscribe method.

API Ref: https://vuex.vuejs.org/en/api.html

Vuex plugins exist for this exact use case as well. Docs: https://vuex.vuejs.org/en/plugins.html

Example:

let vuexPlugin = (store) => {
    let whitelist = ['abc', def', 'ghi'];
    store.subscribe((mutation, state) => {
        if (whitelist.includes(mutation.type)) {
            // your code here
        }
    });
};


来源:https://stackoverflow.com/questions/45132085/vue-listen-for-vuex-commit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!