vuex的深度理解

Vuex是什么

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

为什么用vuex

原先数据需要保存到各自vue实例对象的data中,当使用vuex之后,就可以将data中的数据集中管理到vuex中。让vue中渲染页面的工作和与后台交互的逻辑性的工作分离。使得的代码更加整洁。

vuex的数据维护与vue的数据维护的对比

在vue中,数据是维护在data中的。而转交给vuex,数据是存储在state中的。

vuex的核心概念及深度理解

应用vuex时,首先需实例化。

let store = new Vue.Store({
	state:{},	//用于存储数据状态
	getters:{},	//获取器,类似于vue中computed,可存储从store中的state中派生出的一些状态,如:customers.length
	mutations:{},	//突变,是vuex中唯一可以修改state值的机制,并且这种修改是同步的,不允许包含异步的代码
	actions:{}		//动作,是vuex中唯一可以包含异步操作【异步操作的同步化】不能直接修改state中的值,但是可以通过提交突变的方式修改state中的值
)}
state:是一个对象,用于存储数据状态,使用时,可通过两种方式

1.通过状态机实例对象直接访问

store.state.customers

2.通过计算属性映射(在vue实例中访问)

new Vue({
	el:"",
	store,
	data:{},
	computed:{
		customers:function(){
			return this.$store.state.customers;
			}
		}
	})
mutation:唯一修改state值的机制,并且只能是同步操作。
state:{
	customers:[]
}
mutations:{
	refreshCustomers(state,customers){
	}
}	//state是vue实例化时系统传递给突变的,customers属于改突变一个载荷对象,即参数。

使用:store.commit(“refreshCustomers”,[1,2,3])

action:封装异步操作,不能直接更新state,必须借助mutation来进行更新
//不传参数
actions:{
	async findAllCutomers(context){
		let response = await axios.get();
		context.commit("refreshCustomer",response.data.data)
	},
	//传参数 id
	async deleteCustomerById(context,payload){
		let response = await axios.get("",payload);
		context.dispatch("findAllCustomers")
	}
}
//context是一个与store对象解构相似的对象,包含了commit、dispatch、state

使用:store.dispatch(actionName,payload)

模块化
let customer = {
		 		namespaced:true,
		 		state:{
		 			list:[],
		 			visible:false
		 		},
		 		getters:{

		 		},
		 		mutations:{

		 		},
		 		actions:{

		 		}
		 	},
		 	let category = {
		 		namespaced:true,
		 		state:{
		 			list:[],
		 			visible:false
		 		},
		 		getters:{

		 		},
		 		mutations:{

		 		},
		 		actions:{
		 		
		 		}
		 	}

		 	let store = new Vuex.Store({
		 		modules:{
		 			customer,
		 			category
		 		}
		 	})

		 	new Vue({
		 		computed:{
		 			...Vuex.mapState("customer",["list"])
		 		}
		 	})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值