vuex的状态管理图列

■在上一篇文章中说过可以通过$tore.state.变量 = xxx,来修改state中的值(Vuex概念和作用解析),但这不符合vuex的标准,不推荐使用。

■那么要如何修改state中的值呢

■我们先来看看官方的图

请输入图片描述

■在图中可以看出组件(Vue Components)可以引用vuex的state中的数据

■但修改state需要经过几个步骤

  • 组件发出一个行为调用commit
  • 通过commit提交到mutations修改state

■为什么要通过mutation来修改state中的数据呢

  • 因为vue有一个调式工具devtools,通过commit提交到mutation修改state的值,devtools可以跟踪记录state的变化,直接修改state不能跟踪变化
  • 在开发中state中的数据是多个组件共享的,而每个组件都可以修改state中的数据
  • 直接修改state的话,devtools无法记录是哪个组件修改了state中的数据,不利于调试

在mutations中修改state中的数据

■在mutations中定义修改state数据的方法

  • 通常情况下,Mutations中的方法必须是同步方法
//store\index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:0
  },
  //修改state中的count
  mutations: {
    increment(state){
      state.count++
    },
    decrement(state) {
      state.count--
    }
  },
  actions: {
  },
  modules: {
  }
})

■在其他组件中通过commit提交给mutation修改

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h2>{{$store.state.count}}</h2>
    //点击按钮修改count的值
    <button @click="add()">+</button>
    <button @click="sub()">-</button>
  </div>
</template>

<script>
  export default{
    name: 'About',
    methods:{
        add(){
            //通过commit提交给mutations,触发mutations中对应的事件
            this.$store.commit("increment")
        },
        sub(){
            this.$store.commit("decrement")
        },
    }
  }
</script>

Mutation传递参数

■在通过mutation更新数据时,有可能需要携带一些额外的参数

  • 参数被称为mutation的载荷(Payload)

■组件中的代码

    add(){
        //通过commit提交给mutations,并携带参数
        this.$store.commit("increment",5)
    }

■mutation中的代码

    increment(state,5){
      state.count += 5
    }

■在需要多个参数时

  • 以对象的形式传递,也就是payload一个对象

■组件中的代码

    add(){
        this.$store.commit("increment",{n:5})
    }

■mutation中的代码

    increment(state,payload){
      state.count += payload.n
    }

Mutation的提交风格

■上面的通过commit提交的是一中普通的方式
■Vue还提供了另一个方式,它是一个包含了type属性的对象

组件中的代码

    //普通提交方式
    add(){
        this.$store.commit("increment",{n:5})
    }

    //特殊提交方式,提交一个对象
    add(){
        this.$store.commit({
             type:"increment",
             count:5
        })
    }

mutation中的代码

    increment(state,payload){
      //payload就是commit提交过来的对象
      state.count += payload.count
    }

其他vuex文章

Vuex概念和作用解析
vuex-mutation同步函数
vuex-getters的使用
vuex-actions异步函数
vuex-modules的使用