Use of Vuex (vue2.0)

What is Vuex?

Vuex is a state management pattern + library developed specifically for Vue.js applications . It uses a centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner.

Vuex core concept

state

A single state tree is a single data source, and only one store object is used in a project to store all shared state information. Get data through this.$route.state or mapState

Getters:

Manipulating data, similar to computed properties. Dependent data changes and will be automatically updated​. The method of getting the getter: this.$store.getters​or mapGetters returns the object, saves the computed property, and expands it into computed

mutations:

You can modify the state, define a method in mutations to modify the state, the first formal parameter of the method is state, and the second formal parameter is the data passed from the calling method Call the method in mutations through this.$store.commit or mapMutations into the method

actions:

The processing is asynchronous, the data cannot be modified directly, and the method of triggering mutations is required. Define methods in actions. If you want to modify data, you need to call the methods in mutations. The first formal parameter of actions is similar to $store, use $store.commit() in actions to call the method in mutations​. The method of calling actions: this.$store.dispatch() or mapActions() is placed in the method

module:

Be modular. Modules in the parent component: {place the attributes of the submodule} The submodule is also an object​, the submodule obtains data through $store.state.submodule.property, and generally uses getters for quick access. namespaced:​ By default, the actions, mutations, and getters inside the module are registered in the global namespace and can be called directly globally​. namespaced can ensure the high closure of internal modules, add namespaced: true to the submodule of the parent component, add the path of the module when calling the submodule or use createNamespacedHelpers


foreword

Let's take changing the name of the anime character on the page as an example to demonstrate how to use vuex and introduce some simple specifications


Use vuex example

install vuex

npm i vuex --save

store/index.js

Generally, we recommend creating a store folder under the src path of the project to store all the states, and then import it into main.js

import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";
import getters from "./getters";
Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    user,
  },
  getters,
});

export default store;

main.js

After being introduced into main.js, the reason why we mount the store on the prototype is to use this.$store directly in the project to access all the variables and methods in the state manager

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

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

store/getters.js

We create a unified getters.js file under the store folder, and then manage all the state shortcuts in the project in a unified manner

const getters = {
  name: (state) => state.user.name,
};

export default getters;

store/modules/user.js

We create a modules folder under the store folder for the modularization of vuex, which is convenient for distinguishing the state management of different modules;

namespaced is to enable the namespace to prevent naming conflicts. In general, we recommend enabling it

const state = {
  name: "下忍鸣人",
};
const mutations = {
  EditName: (state, name) => {
    state.name = name;
  },
};
const actions = {
  EditNameAsyc: ({ commit }, name) => {
    setTimeout(() => {
      commit("EditName", name);
    }, 2000);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};

app.vue

1. To use vuex in the page, we generally recommend using the auxiliary function createNamespacedHelpers, which can use the variables and methods in vuex more concisely;

2. Generally, we do not recommend directly using mapState to directly obtain variables. It is recommended to use mapGetters and this.$store to obtain the state of related variables;

3. Note that if you do not use the auxiliary function createNamespacedHelpers, you need to complete the namespace path when using mapMutations and mapActions; for example, when using auxiliary functions...mapMutations(["EditName"]), then you need to do this when not using Write, ...mapMutations(["user/EditName"])

4. When using this.$store to obtain mutations, you need to use the commit method to call related methods; when using this.$store to get actions, you need to use the dispatch method to call related methods

<template>
  <div>
    <div>vuex测试</div>
    <div>原型写法:{
   
   { $store.state.user.name }}</div>
    <div>mapGetters写法:{
   
   { name }}</div>
    <div>mapStates写法:{
   
   { stateName }}</div>
    <button @click="handleChangeName">标签修改姓名</button>
    <button @click="handleChangeNameHelp">辅助函数修改姓名</button>
    <button @click="handleChangeNameAsyc">标签异步改变姓名</button>
    <button @click="handleChangeNameHelpAsyc">标签异步改变姓名</button>
  </div>
</template>

<script>
import { mapGetters, createNamespacedHelpers } from "vuex";
const { mapMutations, mapState, mapActions } = createNamespacedHelpers("user");
export default {
  components: {},
  data() {
    return {};
  },
  computed: {
    ...mapGetters(["name"]),
    ...mapState({
      stateName: (state) => state.name,
    }),
  },
  created() {},
  methods: {
    ...mapActions(["EditNameAsyc"]),
    ...mapMutations(["EditName"]),
    handleChangeName() {
      this.$store.commit("user/EditName", "中忍鸣人");
    },
    handleChangeNameHelp() {
      this.EditName("上忍鸣人");
    },
    handleChangeNameAsyc() {
      this.$store.dispatch("user/EditNameAsyc", "漩涡鸣人仙人模式");
    },
    handleChangeNameHelpAsyc() {
      this.EditNameAsyc("火影鸣人");
    },
  },
};
</script>
<style lang="scss" scoped></style>

expand

1. Why can't I write asynchronous code in mutations? 

After each mutation is executed, it will correspond to a state change, so that devtools can take a snapshot and save it. If the mutation supports asynchronous operations, there is no way to know how the status is updated, and it is impossible to track the status well, which brings difficulties to debugging

2. Vuex does not have the function of persistence, so when doing persistence, it needs to be matched with cache to judge and process

 

Guess you like

Origin blog.csdn.net/yxlyttyxlytt/article/details/131894574