vue状态管理vuex

const store = new Vuex.Store({
		state:{
			name:'jjk',
			age:10
		},   
		mutations:{									  
			change:function(state,a){
				return state.name += a;
			},
			changeAsync:function(state,a){
                console.log(state.num +=a);
            }
		},
		getters:{
			getAge:function(state){                   
                 return state.age;
            }
		},
		actions:{									
			add:function(context,value){			  
                setTimeout(function(){
           //提交事件
                  context.commit('changeAsync',value);
                },1000)   
            }
		}
})

解读

获取:this. s t o r e . s t a t e . n a m e ; t h i s . store.state.name;this. store.state.namethis.store.getters.getAge
修改:this. s t o r e . c o m m i t ( ′ c h a n g e ′ , 10 ) ; t h i s . store.commit('change',10);this. store.commit(change,10);this.store.dispatch(‘add’, 5);
四个主要属性:state;mutations;getters;actions

state

保存组件之间共享信息
直接获取:this.$store.state.name

mutations

显示的更改state里的数据
修改state信息提交:this.$store.commit(‘change’,10)
原理:调用commit方法给mutations中的方法传值
mutations中的方法默认接受两个值一个state,一个commit传进来的值

getters

获取state里的数据
获取需要的存在state的信息this.$store.getters.getAge

actions

异步提交:action中的函数作用是调用mutations中的函数提交修改数据
原理:外部出发action中函数,action中函数触发mutations中函数修改
例如:
外部出发action中的函数:this.$store.dispatch(‘add’, 5);
触发action中的add,action中的add触发mutations中的changeAsync

项目中使用
创建vuex仓库store/index.js这里写图片描述
这里写图片描述
入口main.js
这里写图片描述
修改获取数据
这里写图片描述
获取数据
这里写图片描述
获取方式2
这里写图片描述
这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值