Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe to a store module

Tags:

vue.js

vuex

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.

like image 337
Rikard Avatar asked Oct 20 '17 19:10

Rikard


People also ask

How do I add a store to vue3?

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");

Can you have multiple Vuex stores?

Vuex gives you the flexibility to manage multiple store modules based on how you'd like to structure your project.

What are Vuex modules?

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: { ...


Video Answer


2 Answers

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.

like image 100
beedrill Avatar answered Oct 14 '22 07:10

beedrill


You may try that:

store.subscribe((mutation, state) => {
  const pieces = mutation.type.split('/')
  if (pieces.length > 1) {
    const module = pieces[0]
  }
})
like image 41
Игорь Бадьин Avatar answered Oct 14 '22 06:10

Игорь Бадьин