vuex的基础使用

安装

npm install vuex --save;

目录搭建

-store 
	-store.js
	

使用

// store.js
import vue from 'vue'
import vuex from 'vuex'
vue.use(vuex)
export const store = new vuex.Store({
	state:{
		name:'abc'
	},
	// 获取数据
	getters:{
	 	name : (state) =>{
	 		var changeName = state.name + 'aaa'
	 		return changeName ;
	 	}
	},
	// 触发事件,修改数据
	mutations:{
	   changeName:(state,newValue)=>{
	   		state.name = newValue
	   }
	},
	// 异步; 对mutations的提交进行处理
	actions:{
		changeNameAction:(context,newValue)=>{
		 	setTimeout(()=>{
		 	context.commit('changeName',newValue)
		 	},2000)
		}
	}
})

使用store


this.$store.state.name;
this.$store.getters.name; //...mapGetters(['name'])
this.$store.commit('changeName',''tom') // 调用mutations中的方法
this.$store.dispatch('changeName',''tom') // 调用actions中的方法   等价 ...mapActions(['changeNameAction'])

import {mapGetters,mapMutations,mapActions} from 'vuex'

...mapGetters(['name'])   
...mapMutations(['changeName'])
...mapActions(['changeNameAction']) // 无参数   将this.changeNameAction映射为`this.$store.commit('changeNameAction')
...mapActions({change: 'changeNameAction') // 有参数   使用: this.change('bbb')     将this.change映射为`this.$store.commit('changeNameAction')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值