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)
        },
}
  • 12
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YOLO大师

你的打赏,我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值