vuex四大核心元素

什么是vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

个人理解就是集中管理项目开发中用到的数据,要问什么时候用到vuex。当你构建一个中大型单页面网站的时候可以用到,如果是较为简单的页面反倒最好不要用,会显得繁琐冗余。一个简单的store模式就足够了。

vuex的四大核心元素是state、mutations、actions、getter。

State

state的作用就是存放组件之间的共享数据,也就是说组件之间共享的状态主要存放在state属性中。

state提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。

//创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
	state:{0}
})

组件访问state中数据的第一种方式:

this.$store.state.全局数据名称

组件访问state中数据的第二种方式:

//1.从vuex中按需导入mapState函数
import {mapState} from 'vuex'

通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:

//2.将全局数据映射为当前组件的计算属性
computed:{
	...mapState(['count'])
}

Mutation

不允许直接修改store中的全局数据,而mutation是唯一修改store状态的方法。

1.只能通过Mutation变更Store数据,不可以直接操作Store中的数据。

2.通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

//定义Mutation
const store = new Vuex.Store({
	state:{
		count:0
	},
	mutations:{
		add(state){
			//变更状态
			state.count++  //state中的数据自加1
		}
	}
}) 
//1.触发mutation
methods:{
	handle1(){
		//触发mutation的第一种方式
		this.$store.commit('add')
	}
}

mutation可以传递参数,上面代码是让count加1,传递参数之后可以加n

//定义Mutation
const store = new Vuex.Store({
	state:{
		count:0
	},
	mutations:{
		addN(state,step){
			//变更状态
			state.count += step  //state中的数据自加step
		}
	}
}) 
//1.触发mutation
methods:{
	handle1(){
		//触发mutation的第一种方式
		this.$store.commit('addN',3)  //这里就是使count加3
	}
}

触发mutations的第二种方式:

//1.从vuex中按需导入mapMutations函数
import {mapMutations} from 'vuex'

通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法

methods:{
	...mapMutations(['add','addN'])
}

action

进行异步操作时选择用action,action提交的是mutation,而不是直接变更状态。

//定义Action
const store = new Vuex.store({
	//省略其它代码
	mutations:{
		addN(state,step){
			state.count+=step
		}
	},
	actions:{
		addNAsync(context,step){
			setTimeout(()=>{
				context.commit('addN',step)
			},1000)
		}
	}
})
//触发action
methods:{
	handle(){
		//调用dispatch函数
		this.$store.dispatch('addNAsync',5)
	}
}

触发actions的第二种方式:

//1.从vuex中按需导入mapActions函数
import {mapActions} from 'vuex'

methods:{
	...mapActions(['addAsync','addNsync'])
}

Getter

Getter主要用于对Store中的数据进行加工处理形成新的数据。

Store中的数据发生变化,Getter的数据也会跟着变化。

//定义Getter
const store = new Vuex.Store({
	state:{
		count:0
	},
	getters:{
		showNum:state=>{
			return '当前数为'+state.count
		}
	}
}) 

猜你喜欢

转载自blog.csdn.net/qq_46285118/article/details/127494292
今日推荐