Initial use of Vuex

Introduction to Vuex:
    Vuex is a state management mode specially developed for Vue.js applications.
        It uses centralized storage and management of the state of application components, and uses corresponding rules to ensure that the state changes in a predictable manner;
        Vuex is also integrated into Vue Devtools, the official debugging tool, provides advanced debugging functions such as zero-configuration time-travel debugging, state snapshot import and export.
If we do not use Vuex, then we need to define global variables, but the defined global variables are not in the responsive system of Vue , We also need to set it accordingly, which is very complicated, so there is Vuex to
set global variables:

	const shareObj = {
		name:'pshdhx'
	}
	Vue.prototype.shareObj = shareObj;

This is not reactive;
what state does Vue manage?
    In development, there are often multiple statuses shared between multiple interfaces;
    such as the user's login status, user name, avatar, geographic location information, etc.;
    such as the store's favorites, the items in the shopping cart;
these Status information, we can all put it in a unified place, save and manage it, and they are responsive;
1. Firstly, introduce the Vuex package
    npm install vuex --save to the Vue project
2. Preliminarily establish the Vuex directory structure
    Create a new index.js under the src folder
3. Introduce and register to use vuex in index.js

import Vue from 'vue'
	import Vuex from 'vuex'
	//安装vuex
	Vue.use(Vuex);
	//创建对象
	const store = new Vuex.Store({
		state:{},
		mutations:{},
		getters:{},
		actions:{},
		modules:{}
	})
	//导出store对象
	export default store

4. Register in main.js

import store from '/store'
	new Vue({
		el:'#app',
		store,
		render:h=>h(App)
	})

Initial use of vuex-State, mutations

State is the part that stores state variables. If you want to modify it, you must go through Mutations (a module that stores synchronization request methods), so that you can use the Devtools plug-in to see the changes in the state, which is convenient for debugging when you encounter errors ; If you modify the value in the state directly, the state variables in Devtools will not respond, but will only respond on the page, causing the value on the page to be inconsistent with the value in Devtools, affecting the developer's judgment;

Why do you make a circle to modify the value in state, because what is defined in Actions is an asynchronous method, and what is defined in Mutations is a synchronous method. Different methods are called differently, but in the end they are all modified by calling the method in Mutations. The value of

初步使用vuex-state模块
index.js
const store = new Vuex.Store({
	state:{
		count:100
	},
	mutations:{
		increment(state){
			state.count++
		},
		decrement(state){
			state.count--
		}
	}
})
App.vue
	<button @click="addition">+</button>
	<button @click="subtration">-</button>
<script>
	methods:{
		addition(){
			this.$store.commit('increment')
		},
		subtration(){
			this.$store.commit('decrement')	
		}
	}
</script>

The core concept of Vuex

State,Getters,Mutations,Actions,Modules

Single state

  We know that in China, we have a lot of information that needs to be recorded, such as personal files during school, social security records after work, provident fund records, etc.;

  This information is scattered in many places for management. One day when you need to apply for a household registration, you will find that you need to go to each corresponding work place to print and stamp various information and information, and finally to one place to prove you The information is correct;

The single state management avoids this situation, so all state variables are placed in State for management;

Basic use of Getters

const store = new Vuex.Store({
	State:{
		students:[
			{id:110,name:'pshdhx1',age:18},
			{id:111,name:'psdhhx2',age:20},
			{id:112,name:'pshdhx3',age:22},
			{id:113,name:'pshdhx4',age:25},
		]
	}
})

At this point we have to filter out objects with age>20;

computed:{
	moreThan20(){
		return this.$Store.state.students.filter(age=>age>=20).length;
	}
}
//如果是这样,那么在每个页面中都要定义该计算方法,但是如果定义在vuex中,那么就很方便了;
getters:{
	moreThan20(state){
		return state.students.filter(s => s.age>20).length;
	}
}
//getters中方法的参数中有state,就是index.js中的state
实际上getters中可以返回函数
moreAgeStu(state){
	return function(age){
		return state.students.filter(s=>s.age>age)
	}
	// return age => {return state.students.filter(s=>s.age>age)}
}
//App.vue
<button @click="this.$store.getters.moreAgeStu(20)"></button>

Mutations status update

The only way to update Vuex's store status: submit a mutation

Mutation mainly consists of two parts:

  Event type of string: type

  A callback function handler, the first parameter of the callback function is state

Mutations的定义方式
mutations:{
    state.count++    
}
通过mutation进行更新
increment:function(){
    this.$store.commit('increment');
}
App.vue
methods:{
    addCount(count){
        this.$store.commit('incremntCount',count);
    }
}
mutations:{
    incrementCount(state,count){
        state.counter+=count
    }
}
methods:{
    addStudent(){
        count stu = {id:114,name:'pshdhx5',age:'23'}
        this.$store.commit('addStudent',stu);
    }
}
addCount(count){
    this.$store.commit({
        type:'incrementCount',
        count
    });
}
//这时传递的是count对象;
Mutations:{
    incrementCount(state,payload){
        state.counter+=payload.count
    }
}
state:{
    info:{
        name:'pshdhx6',
        age:40,
        height:170
    }
}

These attributes are added to the responsive system, and the responsive system monitors the changes of the attributes. When the attribute changes, it will notify all the places where the attribute is used in the interface, and let the interface refresh;

updateInfo(state){
    state.info.name='pshdhx7'        //因为name在info中原本就要,所以会响应式改变;包括Devtools
    state.info['address']= '洛杉矶' //因为info中原本没有,所以Devtools不会添加此变量
}

Need to join

Vue.set(state.info,'address','洛杉矶'); //这时变量就添加到了Devtools中
updateInfo(state){
    //该方法做不到响应式
    delete state.info.age
    //该方法可以做到响应式
    Vue.delete(state.info,'age')
}

If an asynchronous request is used in Mutations, the variables in Devtools will not receive a response;

So add asynchronous request to Actions

actions:{
    aUpdateInfo(){
        //context:上下文
        setTimeout(()=>{
            context.commit('updateInfo')
        },1000)
    }
}

At this time, the method in Actions should be called like this in App.vue

methods:{
    updateInof(){
        //this.$store.dispatch('aupdateInfo');
        this.$store.dispatch('aupdateinfo','我是payload');
        //为了可以获得异步请求的调用结果
        this.$store.dispatch('aupdateInfo',()=>{
            console.log('异步请求已经调用完成')
        })

        //也可以这样写:
        this.$store.dispatch('aupdateInfo',{
            payload:'我是携带的信息',
            success:()=>{
                console.log('异步请求已经调用完成');
            }
        })
    }
}

In Actions we write:

actions:{
    aupdateInfo(context,payload){
        setTimeout(()=>{
            context.commit('updateInfo');
            console.log(payload.message);
            payload.success();
        },1000)
    }
}

//或者用promise这样写
actions:{
    aupdateInfo(context,payload){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                context.commit('updateInfo')
                console.log(payload);
                resolve('11111');
            },1000)
        })
    }
}

Because the promise is used in actions, the then callback function can be called in app.vue

this.$store.dispatch('aupdateInfo','我是携带的信息').then(res=>{
    console.log('里面完成了提交');
    console.log(res);
})

First use Modules

Module means module, why use module in Vuex?

Vue uses a single state tree, which means that many states will be managed by Vuex;

When the application becomes very complex, the store object may become very bloated;

In order to solve this problem, Vuex allows us to divide the store into modules, and each module has its own state, mutations, actions, getters, etc.;

const moduleA = {
    state:{},
    mutations:{},
    actions:{},
    getters:{}
},
const moduleB = {
    state:{},
    mutations:{},
    actions:{},
    getters:{}
},
const store = new Vuex.Store({
    modules:{
        a:moduleA,
        b:moduleB
    }
})

store.state.a  //->moduleA的状态
store.state.b  //->moduleB的状态

moduleA is an object in state;

We can use it like this:

{
   
   {this.$store.state.a.name}}
const moduleA = {
    state:{
        name:'pshdhx A'
    },
    mutations:{
        updateName(state,payload){
            state.name = payload
        }
    },
    actions:{},
    getters:{
        fullName(state){
            return state.name+'1111'
        },
        fullNames(state,getters){
            return getters.fullName+'2222'
        },
        funllName3(state,getters,rootState){
            return getters.fullName2+rootState.counter
        }
    }
}

View app

methods:{
    updateName(){
        this.$store.commit('updateName','lisi');
    }
}

<h2>{
   
   {$store.getters.fullName}}</h2>
const moduleA = {
    state:{
        name:'zhangsan'
    },
    mutations:{
        updateName(state,payload){
            state.name = payload
        }
    },
    actions:{
        aupdateName(context){
            setTimeout(()=>{
                context.commit('updateName','wangwu');
            },1000)
        }
    }
}

App.vue
methods:{
    asyncUpdateName(){
        this.$store.dispatch('aupdateName');
    }
}

dispatch object

How to write actions

const moduleA = {
    actions:{
        increment({state,commit,rootState}){
            if((state.count+rootState.count)%2===1){
                commit('increment')
            }
        }
    }
}

If the global state is also needed in the getters, more parameters can be accepted

const moduleA = {
    getters:{
        withRootCount(state,getters,rootState){
            return state.count = rootState.count
        }
    }
}

Project structure of vuex

Note when importing files:

如果是export的是default,那么可以直接import .. from '..';
如果不是,那么需要import {...} from '..';


import mutations from './mutations'
import actions from './actions'
import getters from './getters'

const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})

 

Guess you like

Origin blog.csdn.net/pshdhx/article/details/108275501