vuex:组件中操作state,mutations,actions的方式(vuex的使用方法)

vuex是一个数据管理仓库

官网的图如下:在这里插入图片描述
在组件中操作state,mutations,actions的方式示例如下:
+ store文件的部分代码为:

export default new Vuex.Store({
	state:{
		num:0,
		name:'aa'
	},
	//同步
	mutations:{
		setNum(state){
			state.num++;
		}
		//另一种写法:用ES2015风格的计算属性命名功能来使用一个常量作为函数名
		['setNum2'](state){
			state.num++;
		}
	}
	//异步
	actions:{
		actSetNum(context){
			console.log(context);
			setTimeout(()=>{
				context.commit('setNum')
			},1000)
		}
	}
}) 
  • 组件中操作state

    • 通过this.$store.state
    • 通过计算属性
    computed: {
    	num1: function () {
    		return this.$store.state.num
    	}
    }
    
    • 通过辅助函数
    import {mapState} from 'vuex'
    computed:{
    	...mapState({
    	//num2是计算属性名
    		num2:(state)=>{
    			return state.num
    		}
    	})
    }
    
  • 组件中操作mutations

    • 通过this.$store.commit(‘setNum’) //setNum是mutations的函数名
    • 通过辅助函数
    import {mapMutations} from 'vuex'
    methods:{
    	...mapMutations({
    		fn2:'setNum' //fn2是点击事件的事件名
    	})
    }
    
  • 组件中操作actions

    • 通过this.$store.dispatch(‘actSetNum’) //actSetNum是actions的函数名
    • 通过辅助函数
    import {mapActions} from 'vuex'
    methods:{
    	...mapActions({
    		fn3:'actSetNum' //fn2是点击事件的事件名
    	})
    }
    
vuex的使用示例(传参)
//index.js文件
export default new Vuex.Store({
	state:{
		username:''
	},
	mutations:{
		saveUserName(state,username) {
			state.username = username;
		}
	},
	actions:{
		saveUserName(context,username){
			context.commit('saveUserName',username);
		}
	}
})

//实例中调用
this.$store.dispatch('saveUserName','aa');
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值