天天看点

vuex04Mutations与mapMutations

Mutations是啥------修改修改修改

更改 Vuex 的 store 中的state

在前面我们知道如何去获取state里面的值,可以直接使用state.XX来获取,也可以使用Getter来获取state。

但是我们要如何去更改state,这就是Mutations。

我们要如何调用Mutations的函数呢。

这就要用到commit函数,

const store = new Vuex.Store({
    state: {
        name: "old name",
        age: 18,
    },
    mutations: {
        changName(state) {
            state.name = "newName"
        },
        addAge(state,num) {
            state.age +=num
        },
    }
})      
<template>
  <div>
    <button @click="changeName">我要改名</button>
    <button @click="addAge">我长大啦</button>
    <p>{{name}}</p>
    <p>{{age}}</p>
  </div>
</template>

<script>
export default {
  name: "Home",

  computed: {
    age() {
      return this.$store.state.age;
    },
    name(){ 
    this.$store.state.name
    }
  },
   methods: {
    changeName() {
      this.$store.commit("changName");
    },
    addAge() {
      this.$store.commit("addAge",18);
    },
  }
};
</script>
      

commit提交

上面的例子演示了一种提交的方式

methods: {
    changeName() {
      this.$store.commit({type:"changName"});
    },      

mapMutations

  1. 引入
import { mapMutations } from 'vuex'      
  1. 使用
methods: {
    ...mapMutations([
      'changeName', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    ]),
    ...mapMutations({
      changeName12: 'changeName' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }      

注意:Mutations不要出现异步操作,虽然写了不会报错,程序也能运行,但是官方不建议写。异步操作全部放在action里

比如下面这个例子,一秒钟之后更改名字,其实也可以运行.

mutations: {
        changName(state) {
            setTimeout(() => state.name = "newName"
                , 1000)
        },
}      

继续阅读