天天看點

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)
        },
}      

繼續閱讀