mutations的使用

作用:操作Vuex中的state属性数据。

案例:在HelloWorld组件中单击按钮,实现state中的num数字自增。

错误的代码演示如下。

<template>
  <div class="hello">
    <h1>{{ $store.state.num }}</h1>
    <input type="text" :value="$store.state.num" />
     //1.绑定按钮单击事件
    <input type="button" value="+1" @click="addnum" />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {};
  },
  methods: {
    //2.获取到state中的值,实现自增
    addnum() {
      this.$store.state.num++;
    }
  }
};
</script>

代码解析如下。

上述修改 state 中 num 属性的方法是错误的。运行程序,虽然单击 HelloWorld 中的按钮可以实现自增,但 Vuex 中的值并没有发生变化,修改的只是当前页面中的值。

正确修改 state 中属性值的方法为使用 mutations,代码如下。

Vuex 代码

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    num: 10
  },
  getters: {
    newnum(state) {
      return state.num + '元';
    }
  },
  mutations: {
    //1.定义方法,传入state
    getAdd(state) {
      //2.实现num自增
      state.num++;
    }
  }
});

export default store;

HelloWorld组件代码

<template>
  <div class="hello">
    <h1>{{ $store.getters.newnum }}</h1>
    <input type="text":value="$store.state.num" />
    <input type="button" value="+1" @click="addnum" />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {};
  },
  methods: {
    addnum() {
      // 错误
      // this.$store.state.num++;
      // 正确
      this.$store.commit('getAdd');
    }
  }
};
</script>

代码解析如下。

单击按钮,触发 addnum 方法,在方法中使用 this.$store.commit 触发 mutations 中的方法,运行程序,即可实现 num 数字自增。

mutations 中传递参数:在 HelloWorld 组件中单击自增按钮,可以把 HelloWorld 组件的数据传递到 Vuex 数据仓库中,例如传递数字 100,代码如下。

HelloWorld组件代码

methods: {
    addnum() {
        this.$store.commit('getAdd',100)
    }
}

Vuex代码

mutations: {
  //第二个参数是用户传递的参数
  getAdd(state, data) {
    state.num++;
    // 运行结果为数字 100
    console.log(data);
  }
}

代码解析如下。

用户传递参数时只能传一个参数,如果想传递多个参数,需要使用对象形式,代码如下。

methods: {
  addnum() {
    this.$store.commit('getAdd', { id: 1, name: '小明' });
  }
}

重点:在组件中不能直接修改 state 中的属性值,需要通过 mutations 修改 state 中的属性值。