Can i create local vuex for one difficult component?

Viewed 35

vue2 question
I have many difficult components with same struct

PersonCard
   components
     PersonForm
       components (many components)
       index.vue
     PersonImage
       components (many components)
       index.vue
   index.vue

i want to create vuex instance for one this component, not global. at index.vue for PersonCard folder (root point of component) create vuex, and destroy if component destroy

is it possible?

1 Answers

you can use dynamic modules within your vuex instance. here is a link to read about this technique: vuex dynamic module

but for example imagine you have a website with an admin panel and you don't need state management code to only be available in the admin panel so you can create a vuex store in a js file like:

// store/admin.js
export default {
  namespaces: true,

  modules: {},

  state: () => ({}),

  mutations: {},

  actions: {},

  getters: {},
};

then in the admin root page or component you import this file and do the following:

import adminStore from '@/store/admin;
...
beforeCreate() {
  const hasModule = this.$store.hasModule('admin'); // to make sure you don't register a module that already exists
  if (!hasModule) this.$store.registerModule('admin', adminStore);
},
beforeDestroy() {
  this.$store.unregisterModule('admin'); // removes the admin module when this component destroys
}

and as long as this component is not destroyed you have access to all the vuex functionality using name spaced modules like:

this.$store.dispatch('admin/someActionFromAdminModule')

vuex doc for dynamic modules

Related