Vuex中Mutations修改状态是什么?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
上篇是读取state,这篇是修改状态。即如何操作Mutations。
一. $store.commit( )
Vuex提供了commit方法来修改状态
1.store.js文件
const mutations={
add(state){
state.count++
},
reduce(state){
state.count--
}
}
2.在button上的修改方法
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
二. 传值
最简单的修改状态的操作,在实际项目中我们常常需要在修改状态时传值。比如上边的例子,是我们每次只加1,而现在我们要通过所传的值进行相加。其实我们只需要在Mutations里再加上一个参数,并在commit的时候传递就就可以了。我们来看具体代码:
1.store.js
const mutations={
add(state,n){
state.count+=n
},
reduce(state){
state.count--
}
}
2.修改按钮的commit( )方法传递的参数,我们传递10,意思就是每次加10.
<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
三.模板获取Mutations方法
实际开发中我们也不喜欢看到$store.commit( )这样的方法出现,我们希望跟调用模板里的方法一样调用。
例如:@click=”reduce” 就和没引用vuex插件一样。
1.在模板count.vue里用import 引入我们的mapMutations:
import { mapState,mapMutations } from 'vuex'
2.在模板的<script>标签里添加methods属性,并加入mapMutations
methods:mapMutations([
'add','reduce'
]),
3.在模板中直接使用我们的reduce或者add方法
<button @click="reduce">-</button>
注意:封装起来$store.commit
reduce: function () {
this.$store.commit('add', 10) // html标签是可以不写this
}
补充知识:vuex mutations参数传递
接下来做一个mutations的传参讲解
添加学生的例子
第一种传参的方式
<template>
<p>
<h4>-------------------这是mutations传参测试-------------------</h4>
<p>
{{this.$store.state.students}}//将已经有的学生渲染在这儿
<p>
<button @click="addstu">点击添加</button>//绑定添加事件
</p>
</p>
</p>
</template>
<script>
export default {
methods: {
addstu () {
const newstu = {
id: 5,
name: '张国荣',
age: 44
}//定死一个要添加的学生,这就是要传给mutations的参数
this.$store.commit('addStudent', newstu)
//调用commit方法,更新state的数据,
//第一个参数是mutations里面的方法名,
//第二个参数是传给mutaitons里面addstudent方法的一个参数,
//也就是要新加入的学生
}
}
}
</script>
在vuex.store中接收这个参数
const store = new Vuex.Store({
// 定义的公共变量
state: {
count: 1,
students: [
{
id: 1,
name: 'dx',
age: 18
},
{
id: 2,
name: 'yx',
age: 18
},
{
id: 3,
name: 'ym',
age: 32
},
{
id: 4,
name: '刘亦菲',
age: 30
}
]
},
// state中的变量只能在mutations中通过方法修改
mutations: {
changeCount: function (state) {
state.count++
console.log('改变了count')
},
addStudent (state, stu) {
state.students.push(stu)
}//通过这种方式,接收来自组件传过来的新加入的学生
},
actions: {
},
getters: {
}
})
第二种传参的方式
组件向vuex传参
addstu () {
const newstu = {
id: 5,
name: '张国荣',
age: 44
}
this.$store.commit({
type: 'addStudent',
newstu: newstu
})//原先是传入两个参数,现在直接传入一个对象
//type就是需要调用的mutations里面的方法
//newstu就是要求接收的对象,也就是新加入的学生
}
vuex接收组件传参
mutations: {
addStudent (state, playload) {
state.students.push(playload.newstu)
}
},
需要注意的是,addstudent接收到的第二个参数是一个完整的对象,所以参数的使用略微有点不同
关于Vuex中Mutations修改状态是什么问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。