vuex 核心概念 mutations

二、mutations修改

之前在基本使用里面,已经对mutations进行了简单的使用。实际上,mutations 包含 事件、回调函数、参数。
即 ,

mutations :{
    
    
	[event] : function CallBack( state, payload ){
    
     }
}

注意:这个传入的state, payload 参数,如果只传一个,那么默认当它是state,直接访问vuex里面的state数据,即便你是(anotherName);
payload ,如果只写一个payload参数,那么他会收到一个参数,写多个它并不会传过来,那么payload怎么传多个?
用payload传一个对象{}

完整的mutations用法:

// ./src/store/index.js
const store = new vuex.Store({
    
    
	mutations: {
    
    
		onAdd(state,amount){
    
      state.counter+=amount; }
	}
});

// ./src/components/app.vue
    <button @click = "btnAdd(15)">ADD</button>
	<script>
export default {
    
    
  name: 'Cxw',
  methods:{
    
    
      btnClick(amount){
    
    
      //传递参数给vuex中的mutations
         this.$store.commit('onAdd',amount);
      }
  }
};
</script>

注意:
有个commit提交风格的一个封装写法,即

this.$store.commit({
    
    
	type: 'onAdd',
	amount: amount,
	gg: 'gg'
})

此时,在src/store/index.js中,接收到的是这样的:

mutations:{
    
    
	onAdd(state, obj){
    
    
		obj.type;//'onAdd'
		obj.amount;//15
		obj.gg;//'gg'
	}
}
可以看到,obj= {
    
    type: 'onAdd',
	amount: amount,
	gg: 'gg'}

Mutations 开发常用方法

一般,在项目开发过程中,你要在mutations里面写函数名,又要在app.vue里面写函数名,重复了,而且容易写错,因此,官方推荐使用常量写法,即,把函数名定义成外部的一个常量,然后导入。

具体实现:
1、新建/src/store/mutations-type.js 文件
2、在里面写出所有使用到的方法的名字,以字符串存储

//mutations-type.js
export const INCREMENT = "increment";

//index.js
{
    
    
	mutations: {
    
    
		[INCREMENT](state, obj) {
    
     // ...代码}
	}
}

//app.vue
{
    
    
	methods:{
    
    
		add(cnt){
    
     
			this.$store.commit(INCREMENT,cnt);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42557786/article/details/115180708