I am aware that in Vuex we can do store.subscribe
and we pass a callback that is called on every change in the store.
In my app I have a store with many modules and would like to subscribe
only to a specific Module and not have to have this kind of logic if (mutation.type != thisModule.type) return;
.
Is it possible to subscribe only to some Modules? Could not find it in the docs.
Adding Vuex to your Vue 3 Projectimport { createApp } from "vue";import { createStore } from "vuex";// Create a new store instance or import from module. const store = createStore({ /* state, actions, mutations */});const app = createApp();app. use(store);app. mount("#app");
Vuex gives you the flexibility to manage multiple store modules based on how you'd like to structure your project.
To help with that, Vuex allows us to divide our store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules - it's fractal all the way down: const moduleA = { state: () => ({ ... }), mutations: { ...
I had the same problem and came across with this question, according to this link: https://forum.vuejs.org/t/vuex-subscribe-and-modules/36049 Subscription is always global.
My work around is to check the mutation in each subscription:
Suppose you have a module 'yourmodule' for subscription, you can do:
store.subscribe((mutation, state) => {
if (mutation.type.startsWith("yourmodule")){
//do your stuff here
}
})
The mutation.type will give the actual mutation name, such as 'yourmodule/yourcommit', I use startswith() method to check because none of my modules starts the same, but you can use more accurate check for your own project.
You may try that:
store.subscribe((mutation, state) => {
const pieces = mutation.type.split('/')
if (pieces.length > 1) {
const module = pieces[0]
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With