Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue listen for Vuex commit?

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.

like image 527
Stephan-v Avatar asked Jul 16 '17 18:07

Stephan-v


1 Answers

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
        }
    });
};
like image 130
pretzelhammer Avatar answered Oct 05 '22 18:10

pretzelhammer