vuex几大模块和Vuex助手使用详解

2023年1月3日09:59:52

Vuex 是一个专为 Vue.js 应用程序开发的状态管理库,用于保存用用程序的状态,即信息或数据,使得Vuex使应用程序的所有组件可以共享数据。每一个 Vuex 应用的核心就是 store(仓库),包含着你的应用中大部分的状态 ( state ),改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。

1、Vuex主要有以下几个模块

  1. state:定义了应用程序的数据,可以设置默认的初始状态。
  2. getters:允许组件从 store 中获取数据 。
  3. mutations:是唯一更改 store 中状态的方法,且必须是同步函数。但不可以直接调用mutation,必须使用commit函数来告诉Vuex更新存储并提交更改。
  4. actions:执行异步操作来存取状态,但也不可以直接调用action,必须使用dispatch函数来执行。
    代码演示:
<script>
	const store = new Vuex.Store({
		//定义状态,并赋予初始值
		state:{
			msg:'Vuex的使用',
			count:0
		},
		//使用getter来返回状态
		getters:{
			msg(state){
				return state.msg;
			},
			count(state){
				return state.count;
			}	
		},
		//可以理解为其他语言中的setter,改变状态的值,此处为把传进来的参数step累加到count中
		mutations:{
			increment(state,step){
				state.count += step;
			}	
		},
		//模拟服务器延迟1秒
		//通过commit调用来触发mutations对象中的increment方法,并把参数step传递给increment
		actions:{
			increment(context,step){
				setTimeout(function(){
					context.commit('increment',step);
				},1000);
			}	
		},
	});
	//创建Vue实例
	let vm = new Vue({
		el:'#app',
		
		computed:{
			//可以直接通过计算属性直接获取store.state中的状态
			msg(){
				return store.state.msg;
			}
			//通过计算属性来返回getters中的count
			counter(){
				return store.getters.count;
			}
		},
		methods:{
			increment(){
				//调用dispatch方法来派发actions中的increment方法,并把参数2传递给increment
				store.dispatch('increment',2);
			}
		}
	});
</script>

2、Vuex助手

Vuex为我们提供了一些辅助工具,如mapStates,mapGetters,mapMutations,mapActions,从而来减少繁杂的工作量。
对于使用mapStates,mapGetters,可以把所有的state,getter添加到计算属性中,而不用向上面代码那样逐个添加。
在使用这些助手时,必须引入。拿mapGetters举例,其他类似。

import {mapGetters} from 'vuex';

代码演示:

computed:{
	...mapState{[
		'state1',
		'state2',
	]},
	...mapGetters{[
		'count1',
		'count2',
	]}
}

对于mapMutations,mapActions,可以在methods属性中使用,把多个mutation和action映射到应用程序。
代码演示:

methods:{
	...mapMutations([
		//mut1将this.mut1()映射到this.$store.commit('mut1'),mut2类似
		//这样就不同创建每个方法,派发每个action
		'mut1',
		'mut2'
	])
}

代码演示:

methods:{
	...mapActions([
		//act1将this.act1()映射到this.$store.dispatch('act1'),act2类似
		'act1',
		'act2'
	])
}

3、Vuex模块

当应用程序很大时,需要划分模块,Vuex.Store实例中将增加mudules对象。
把state,getter,mutation,action对象创建在一个单独的xxx.js文件中,xxx.js在modules目录下。
代码演示:

const state = {
	state1:{}
};
const getters = {
	get1:state => state.state1
};
const actions = {
	initState:{}
};
const mutations = {
	setState:{}
};

//导出以上四个对象
export default{
	state,
	getters,
	mutations,
	actions
}

使用模块,在yyy.js文件中引入模块,yyy.js在store目录下。
代码演示:

import Vue from 'vue';
impoet Vuex from 'vuex';
import xxx from './modules/xxx';

Vue.use(Vuex);

export const store = new Vuex.Store({
	modules:{
		//对应上面引入的xxx
		xxx
	}
});

另外,由于Vuex中所有内容共享相同的全局名称空间,当在两个不同文件中分别命名相同的state或getter或mutation或action,就会发生冲突,报错duplicate getter key。
可以在Vuex.store文件顶部设置namespaced:true,用于分解每个名称空间的模块。

  • 作者:呆石头
  • 原文链接:https://blog.csdn.net/weixin_42273504/article/details/106155881
    更新时间:2023年1月3日09:59:52 ,共 2314 字。