Vuex Mutations的正确使用

这篇博客介绍了如何在 Vue.js 应用中使用 Vuex 创建 store,并定义同步与异步的 mutations 方法。通过 `this.$store.commit` 调用 mutations,展示了在 Vue 组件中如何更新 state 的计数器,同时讨论了异步 mutations 中的注意事项,即不要在 mutation 中进行异步操作以确保 devtools 能正确追踪状态变化。
摘要由CSDN通过智能技术生成

 store.js中声明Mutations中的方法:

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

Vue.use(Vuex)
Vue.config.devtools = true
export default new Vuex.Store({
  state: {
    count: 10
  },
  mutations: {
    addCount(state, num) {
      state.count += num;
    },
    // payload载荷获取传入的额外参数
    // addCount(state, payload) {
    //   state.count += payload.num;
    // },
    // 不要在这里异步操作,devtools监测不到属性值的变化
    addCountAsyn(state, num) {
      setTimeout(() => {
        state.count += num;
      }, 1000);
    } 
  }
})

App.vue使用this.$store.commit调用Mutations中的方法:

<template>
  <div id="app">
    <!-- <button @click="countHandler">计算</button> -->
    <button @click="addCount">同步计算</button>
    <br>
    <br>
    <button @click="addCountAsyn">异步计算</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {

    }
  },
  components: {

  },
  methods: {
    // countHandler() {
    //   // state默认只有getters,不能使用下面这种操作,修改状态的唯一方法是提交mutation
    //   this.$store.state.count ++ ;
    // },
    addCount() {
      // 第一个参数:mutations中声明的函数名;第二个参数:要传递的数据
      this.$store.commit('addCount', 5);
      // 第1种方式传入额外的参数,mutations中使用载荷payload
      // this.$store.commit('addCount', {num: 5});
      // 第2种方式传入额外的参数
      // this.$store.commit({
      //   type: 'addCount',
      //   num: 5
      // })
    },
    addCountAsyn() {
      this.$store.commit('addCountAsyn', 10);
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

页面效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值