Use of vuex namespace

Use of vuex namespace

Since Vuex uses a single state tree, all application states are concentrated into a relatively large object. When your application becomes very complex, the store object may become quite bloated.

Therefore, Vuex allows us to split the store into modules, each of which has its own state, mutation, action, getter, and even nested submodules.

By default, actions, mutations, and getters inside a module are registered in the global namespace, allowing multiple modules to respond to the same mutation or action. If you want your module to have higher encapsulation and reusability, the concept of namespace is used.

{
    "Module 1":{
        state:{},
        getters:{},
        mutations:{},
        actions:{}
    },
    "Module 2":{
        state:{},
        getters:{},
        mutations:{},
        actions:{}
    }
}

The first parameter of mapState, mapGetters, mapMutations, and mapActions is a string (namespace name), and the second parameter is an array (no need to rename)/object (need to rename).

mapXXXs('namespace name',['attribute name 1','attribute name 2'])

mapXXXs('namespace name',{

  'New name 1 in component': 'Original name 1 in Vuex',

  'New name 2 in component': 'Original name 2 in Vuex',

})

Project Structure

mian.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

index.js

import Vue from "vue";
import Vuex from "vuex";
import cat from "./modules/cat";
import dog from "./modules/dog";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: { cat, dog }
});

cat.js

export default {
  namespaced: true,
  // local state: {
    name: "Blue and White British Shorthair",
    age: 1
  },
  // Local read getters: {
    desc: state => "Pet: " + state.name
  },
  // Local changes mutations: {
    increment(state, payload) {
      state.age += payload.num;
    }
  },
  // Local actions actions: {
    grow(context, payload) {
      setTimeout(() => {
        context.commit("increment", payload);
      }, 1000);
    }
  }
};

dog.js

export default {
  namespaced: true,
  // local state: {
    name: "Labrador",
    age: 1
  },
  // Local read getters: {
    desc: state => "Pet: " + state.name
  },
  // Local changes mutations: {
    increment(state, payload) {
      state.age += payload.num;
    }
  },
  // Local actions actions: {
    grow(context, payload) {
      setTimeout(() => {
        context.commit("increment", payload);
      }, 1000);
    }
  }
};

hello.vue

<template>
  <div class="hello">
    <h3>Vuex state tree</h3>
    <div>{{this.$store.state}}</div>
    <h3>mapState</h3>
    <div>{{catName}} {{catAge}}</div>
    <div>{{dogName}} {{dogAge}}</div>
    <h3>mapGetters</h3>
    <div>{{catDesc}}</div>
    <div>{{dogDesc}}</div>
    <h3>mapMutations</h3>
    <button @click="catIncrement({num:1})">Cat changes</button>
    <button @click="dogIncrement({num:1})">Dog changes</button>
    <h3>mapActions</h3>
    <button @click="catGrow({num:1})">Cat Action</button>
    <button @click="dogGrow({num:1})">Dog action</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";

export default {
  name: "HelloWorld",
  computed: {
    ...mapState("cat", {
      catName: "name",
      catAge: "age"
    }),
    ...mapState("dog", {
      dogName: "name",
      dogAge: "age"
    }),
    ...mapGetters("cat", {
      catDesc: "desc"
    }),
    ...mapGetters("dog", {
      dogDesc: "desc"
    })
  },
  methods: {
    ...mapMutations("cat", { catIncrement: "increment" }),
    ...mapMutations("dog", { dogIncrement: "increment" }),
    ...mapActions("cat", { catGrow: "grow" }),
    ...mapActions("dog", { dogGrow: "grow" })
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>

Operation effect

This is the end of this article about the use of vuex namespace. For more relevant vuex namespace content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement modular settings of vuex in nuxt framework
  • Detailed explanation of the modular splitting practice of Store under Vuex
  • Learn vuex and modularity through a simple example
  • In-depth understanding of Vuex modularity (module)
  • A brief discussion on the namespace of store in vuex
  • Vuex modularization and namespaced example demonstration

<<:  Examples of using temporary tables in MySQL

>>:  Detailed explanation of the functions of each port of Tomcat

Recommend

Server concurrency estimation formula and calculation method

Recently, I need to stress test the server again....

Based on JavaScript ES new features let and const keywords

Table of contents 1. let keyword 1.1 Basic Usage ...

HTML table border control implementation code

Generally, when we use a table, we always give it...

Docker cleanup environment operation

Start cleaning carefully! List unused volumes doc...

MySQL database rename fast and safe method (3 kinds)

Table of contents How to rename MySQL database Th...

Detailed explanation of how to mount remote file systems via SSH on Linux

Features of SSHFS: Based on FUSE (the best usersp...

Detailed explanation of screen command usage in Linux

GUN Screen: Official website: http://www.gnu.org/...

Vue Element-ui form validation rule implementation

Table of contents 1. Introduction 2. Entry mode o...

Implementation code of Nginx anti-hotlink and optimization in Linux

Hide version number The version number is not hid...

A brief summary of vue keep-alive

1. Function Mainly used to preserve component sta...

Summary of various forms of applying CSS styles in web pages

1. Inline style, placed in <body></body&g...

WeChat applet realizes left-right linkage

This article shares the specific code for WeChat ...

Some tips on speeding up the development of WeChat mini-programs

1. Create a page using app.json According to our ...

Supplementary article on front-end performance optimization

Preface I looked at the previously published arti...