1-15 vux之mutation

mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,所以mutation就是用来修改store状态集中state的数据的,我们需要一个小示例,来看他是如何实现。
首先先定义mutations.js

	//放的commit提交的mutation
	change_erom(state,payload){//1.数据,2.传过来的数据
		state.room = payload			//修改state数据集中的room
	}

定义好方法以后,我们只要触发这个方法就可以进行数据的修改。

到需要修改数据的组件里:

html部分:

  <div id="app">
<template>
  <div id="app">
	  <!-- {{userName}} -->
	  {{getName}}
	  {{getUserName}}
	  {{room}}
	  <button @click="change"></button>
  </div>
</template>
  </div>

js部分:

import { mapState,mapGetters,mapMutations} from 'vuex'		//将mapMutations解构出来
export default {
  methods:{		//这里注意,mapMutations需要在methods里面展开
	  ...mapMutations(['change_erom']),
	  //如果是子组件的Getters,采用以下方式进行展开
	    ...mapGetters('user',['getUserName'])
	  change(){		//定义的点击事件
		  //同步		提交mutation类型有以下两种方法
		  //1.
		  // this.$store.commit("change_erom",'302')
		    // this.$store.commit("user/change_erom",'302')
			//2.
		  this.change_erom('300')
	  }
  }
}

以上方式采用vuex辅助方法进行修改,如有不懂,可以看api

发布了38 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39162041/article/details/104755683
今日推荐