Vue uses Vuex to package and use store step by step

One, install Vuex dependencies

cnpm install vuex --save

2. Package store step by step

1. Globally import store warehouse in main.js (create next step)

import store from './store' //引入store
 
new Vue({
    
    
  el: '#app',
  router,
  store, //挂载store,this将自动生成$store属性
  template: '<App/>',
  components: {
    
     App }
})

Mount the store, this will automatically generate the $store attribute

2. this.$store

Create store warehouse: It is customary to create a store folder under src, and then create index.js, the content:

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store();
 
export default store;

At this point you already have an empty store global warehouse, without any functions, but you canUnder any vue instanceuse this.$store Go visit it.

  • The scope of use of the store can be used globally;
  • let a=1; {a:a}.a 的缩写是 {a}.a,即当字典的键和值命名一样时,可以省略只写a
  • State, getters, mutations, and mutations are all special variables encapsulated by Vuex. The function variables declared below are all these names. One advantage is that the store can be abbreviated when mounting the function (such as 3-1, in this example). Of course, you can also write functions directly in the store (such as 3-2).

3. this.$store.state

Read data function for store warehouse: state

/*********  3-1 **********/
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
 const state={
    
     //要设置的全局访问的state对象,赋予初始属性值
     themeColor: {
    
    val:'blue',opacity:false},
     changeThemeCount:0,
     cache:''
   }; 
 const store = new Vuex.Store({
    
    
       state
    });
 
export default store;

At this point, your store has the function of accessing data, you can use this.$store.state.themeColorWait for the data.
The following is the second way of writing

/*********  3-2 **********/
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

const store = new Vuex.Store({
    
    
      state:{
    
    
       	 //要设置的全局访问的state对象,赋予初始属性值
	     themeColor: {
    
    val:'blue',opacity:false},
	     changeThemeCount:0,
	     cache:''
       }
    });
 
export default store;

4. this.$store.getters (upgrade of this. $store.state)

Upgrade the state function so that it has computing power (similar to the computed method in vue): getters:

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
 const state={
    
     //要设置的全局访问的state对象,赋予初始属性值
     themeColor: {
    
    val:'blue',opacity:false},
     changeThemeCount:0,
     cache:''
   }; 
const getters = {
    
       //实时监听state值的变化(最新状态)
    getThemeColor(state) {
    
      //定义函数,返回处理过的val,命名最好有代表性
       let hour = new Date().getHours();
       // 如果白天则主题色不透明,反之
       state.themeColor.opacity = 8 <= hour && hour <= 20;
       return state.themeColor
    }
};
const store = new Vuex.Store({
    
    
       state, // 挂载存取数据功能
       getters //挂载数据计算功能
});
export default store;

Use at this time this.$store.getters.getThemeColor Get the color, will automatically set whether the theme has a transparent effect according to the time

5. this.$store.commit(‘mutations’)

Use function function for store warehouse (only for manipulating state data): mutations-synchronization

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
 const state={
    
     //要设置的全局访问的state对象,赋予初始属性值
     themeColor: {
    
    val:'blue',opacity:false},
     changeThemeCount:0,
     cache:''
   }; 
const getters = {
    
       //实时监听state值的变化(最新状态)
    getThemeColor(state) {
    
      //定义函数,返回处理过的val,命名最好有代表性
       let hour = new Date().getHours();
       // 如果白天则主题色不透明,反之
       state.themeColor.opacity = 8 <= hour && hour <= 20;
       return state.themeColor
    }
};
const mutations = {
    
    
    //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
    clearCatch(state) {
    
     
        state.cache = "";
        state.changeThemeCount= 0;
    },
    setThemeColor(state,color,opacity){
    
     
       state.themeColor.val = color;
       state.themeColor.opacity = opacity;
       state.changeThemeCount++;
    }
};
const store = new Vuex.Store({
    
    
        state, // 挂载存取数据功能
       getters, //挂载数据计算功能
       mutations // 挂载函数功能
});
export default store;

You can use this.$store.commit(‘setThemeColor’,‘grey’,‘1’)(Note that the first parameter is the function name, not the parameter passed to the state, the state itself will pass, and the latter two are the corresponding parameters). You can actively set the theme color and transparency, and the operation is synchronous, that is, if you call the setThemeColor function multiple times in the same component, the value of state.changeThemeCount in the warehouse is the same. The asynchronous function is introduced below.

6. this.$store.dispatch('actions') (upgrade of this. $store.commit('mutations'))

Upgrade the function commit function of store warehouse (only for functions in asynchronous operation mutations): actions-asynchronous

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
 const state={
    
     //要设置的全局访问的state对象,赋予初始属性值
     themeColor: {
    
    val:'blue',opacity:false},
     changeThemeCount:0,
     cache:''
   }; 
const getters = {
    
       //实时监听state值的变化(最新状态)
    getThemeColor(state) {
    
      //定义函数,返回处理过的val,命名最好有代表性
       let hour = new Date().getHours();
       // 如果白天则主题色不透明,反之
       state.themeColor.opacity = 8 <= hour && hour <= 20;
       return state.themeColor
    }
};
const mutations = {
    
    
    //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
    clearCatch(state) {
    
     
        state.cache = "";
        state.changeThemeCount= 0;
    },
    setThemeColor(state,color,opacity){
    
     
       state.themeColor.val = color;
       state.themeColor.opacity = opacity;
       state.changeThemeCount++;
    }
};
const actions = {
    
    
    //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性
    setThemeColorAction(context,color,opacity){
    
    
     	context.commit('setThemeColor',color,opacity);
    }
};
const store = new Vuex.Store({
    
    
       state, // 挂载存取数据功能
       getters, //挂载数据计算功能
       mutations, // 挂载函数功能
       actions, // 挂载异步函数
});
export default store;

You can use this.$store.dispatch(‘setThemeColorAction’,‘grey’,‘1’)(Note that the first parameter is the function name, not the parameter passed to the context, the context itself will pass, and the latter two are the corresponding parameters). You can actively set the theme color and transparency, and the operation is asynchronous, that is, if you call the setThemeColorAction function multiple times in the same component, the value of state.changeThemeCount in the warehouse will not be the same.

Three, modules modular

The second module introduces the four functions of the store repository: state, getters, mutations and actions. The fifth function is introduced below: modules.

  • When the project is relatively large, the data in a store will be very large and complex, which is not easy to manage. At this time, multiple "sub-warehouses" can be built to read and manipulate data corresponding to different modules.
  • Note that the main warehouse is still that one, just put his "sub-repository" under the modules of the main warehouse.
  • The sub-repository looks a lot like a warehouse. In fact, it is not an instance of a store, not a warehouse (the object after instantiation of new Vuex.Store() is a warehouse), but a normal js object (dictionary).

1. Create a new modules folder under store, and create a new home.js "sub-repository" under modules.
Insert picture description here
That is, home.js only cares about the data under the homepage (generally don’t divide too much, at most one page and one warehouse are concise), the following is home.js code

//home.js

const state={
    
    
    users:[] //存访问该页面的所有用户
};
const getters={
    
    
  getUsers(state){
    
     //获取访问该页面的所有用户
    // 对数据清理-除去脏数据
  	if (state.users.includes('*')) delete state.users['*'] 
    	return state.users;
  }
};
const mutations={
    
    
     addUser(state,name){
    
     //增加访问用户
        state.collects.push(name)
     }
 };
const actions={
    
    
    invokeAddUser(context,name){
    
     //触发mutations里面的addUser,传入数据形参name对应到users
        context.commit('addUser',name);
    }
};
// 注意和仓库的区别
const store = {
    
    
     // namespaced用于在全局引用此文件里的方法时标识这一个的文件名,使得让人明白这些数据来自哪个仓库
     // 即当你需要在别的文件里面使用子仓库(mapStates、mapGetters、mapActions)时,里面的方法需要注明来自哪一个模块的方法
     namespaced:true,
     state,
     getters,
     mutations,
     actions
}
export default store;

2. The "sub-repository" has been created, and the main warehouse must reference it:

import Vue from 'vue';
import Vuex from 'vuex';
import home from './modules/home.js'

Vue.use(Vuex);
 const state={
    
     //要设置的全局访问的state对象,赋予初始属性值
     themeColor: {
    
    val:'blue',opacity:false},
     changeThemeCount:0,
     cache:''
   }; 
const getters = {
    
       //实时监听state值的变化(最新状态)
    getThemeColor(state) {
    
      //定义函数,返回处理过的val,命名最好有代表性
       let hour = new Date().getHours();
       // 如果白天则主题色不透明,反之
       state.themeColor.opacity = 8 <= hour && hour <= 20;
       return state.themeColor
    }
};
const mutations = {
    
    
    //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
    clearCatch(state) {
    
     
        state.cache = "";
        state.changeThemeCount= 0;
    },
    setThemeColor(state,color,opacity){
    
     
       state.themeColor.val = color;
       state.themeColor.opacity = opacity;
       state.changeThemeCount++;
    }
};
const actions = {
    
    
    //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性
    setThemeColorAction(context,color,opacity){
    
    
     	context.commit('setThemeColor',color,opacity);
    }
};
const store = new Vuex.Store({
    
    
       state, // 挂载存取数据功能
       getters, //挂载数据计算功能
       mutations, // 挂载函数功能
       actions, // 挂载异步函数
       modules:{
    
     // 挂载子仓库
         home
    	}
});
export default store;

Now there is the first "sub-warehouse"!

Fourth, use the warehouse

1. No map series

Suitable for fewer use
cases : build a warehouse, and directly use state, getters, mutations, and actions in components:

  • this.$store.state.*
  • this.$store.getters.*
  • this.$store.commit.*
  • this.$store.dispatch.*

2. Map mapping series

Suitable for frequent use scenarios:
1. Import is required before using mapGetters, mapActions and mapStates:

import {
    
    mapState,mapGetters,mapActions} from 'vuex';

2. Use ES6 new syntax-Hyper reference, Map out all the data or methods under a certain function for use. The following are examples of mapState, mapGetters, and mapActions:

	//这里的...是超引用,映射内容,可以写在computed下、methods下等(一般放在开头)
	// 直接从库中取值 - 将库里的users值返回给字典中的users并映射给this组件
 	...mapState({
    
      
         users:state=>state.home.users  
      }),
     // 使用计算属性 - 将库里的users计算后的值返回给字典中的users并映射给this组件
    ...mapGetters('home',{
    
     
         users:'getUsers' //获取清理后的数据
         //由于home仓库 namespaced:true,所以第一个参数作为标识
         // 不使用标识访问的是主仓库
      })
      // 使用异步函数 - 以数组中的函数名,从库中对应的函数映射给this组件以供使用
    ...mapActions('home',['invokeAddUser'])
    // 有某个组件 <span @click='invokeAddUser(name)'></span>
    // 或者直接使用 this.invokeAddUser(name)

3. Expansion

1、mapState映射的三种写法
  computed: mapState({
    
    
   // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
    
    
      return state.count + this.localCount
    }
  })
  
2、当映射的计算属性的名称与state的子节点名称相同时,
   我们也可以给 mapState传一个字符串数组。
  computed: mapState([ // 数组
   "count"
  ])
  
3、仓库中action的第二种接收参数
const actions = {
    
    
    //自定义触发mutations里函数的方法,{commit}与store 实例具有相同方法和属性
    setThemeColorAction({
    
    commit},color,opacity){
    
    
     	commit('setThemeColor',color,opacity);
    }
};

3. Summary

1. Vuex is a centralized state management architecture specially designed for Vue.js applications. It draws on the design ideas of Flux and Redux, but simplifies the concept, and adopts a specially designed implementation to better utilize the Vue.js data response mechanism.

2. The four core concepts of Vuex are:
The state tree: Vuex uses a single state tree, and one object contains all application-level states. So far it exists as a "single data source (SSOT)". This also means that each application will only contain one store instance. The single-state tree allows us to directly locate any specific state segment, and easily obtain a snapshot of the entire current application state during debugging.
Getters: Used to get Vue component data from the store.
Mutators: Event handlers are used to drive state changes.
Actions: Functions that can be used by components to drive event handler mutations

3. The flow of data in the Vuex application (Vuex official map)
Insert picture description here

  • Data flow is one-way
  • Component can call action
  • action is used to dispatch mutation
  • Only mutation can change state
  • The store is responsive, no matter when the state is updated, the components will be updated synchronously

References:
Thinking about whether or not-Leaping and
thinking about whether or not

Guess you like

Origin blog.csdn.net/GeniusXYT/article/details/106084065