站长资讯网
最全最丰富的资讯网站

在Vuex中Mutations修改状态操作下详解

在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>  <h3>-------------------这是mutations传参测试-------------------</h3>  <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接收到的第二个参数是一个完整的对象,所以参数的使用略微有点不同

相关学习推荐:javascript视频教程

赞(0)
分享到: 更多 (0)

网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号