更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutations 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。mutation 必须是同步函数

    /** 
     * 1) 包含多个直接更新 state 的方法(回调函数)的对象 
     * 2) 只能包含同步的代码, 不能写异步代码 
     * 3) 唯一改变state状态的地方,直接更改
     * 4) 谁来触发: 组件中:this.$store.commit('mutation 名称',data)
    */

mutations唯一的目的是修改state中的状态,mutations中的方法可能完成的事件比较单一一点,复杂的逻辑处理放到actions中(actions不仅主要用来处理异步,还可用来处理逻辑)

提交方式一:不带载荷(只改变数据的状态)

接前面几篇文章的例子,这里我们修改商品价格减半。

store.js

    mutations: {
        //商品价格减半;更改这个数据状态必须将这个数据源state传递过来
        goodsPriceHalve: state => {
            let goodsPriceHalve = state.goodsList.map(currentValue => {
                return {
                    name: currentValue.name,
                    price: currentValue.price/2
                }
            })
            state.goodsList = goodsPriceHalve;
        }
    }

page5.vue

要唤醒一个 mutation handler,你需要以相应的 type(事件) 调用 store.commit 方法。

<template>
    <div>
        <h2>我是第三个页面</h2>
        <!-- 直接在HTML标签中使用 -->
        <div>{{$store.state.goodsList}}</div>
        <br>
        <router-link to='/page6'>更改商品名字</router-link>
        <br>
        <button @click="handleGoodsHavle">商品价格减半</button>
        <ul class="ul_list">
            <li v-for="item in goodsListHalv">
                <p class="name">商品:{{item.name}}</p>
                <p class="price">价格:¥{{item.price}}</p>
            </li>
        </ul>
    </div>
</template>
<script>
  export default {
     data() {
        return {
            /*
            // mutations不能通过直接赋值的形式改变state的数据状态
            goodsListHalv: this.$store.state.goodsList,
            */
            // goodsListHalv: []
        }
      },
      /*
    //   mutations不能通过钩子函数的形式进行赋值
      mounted(){
         this.goodsListHalv = this.$store.state.goodsList
    },
    */
    // 通过计算属性的方式,是完美的
      computed: {
          goodsListHalv(){
              return this.$store.state.goodsList;
          }
      },
      methods: {
          handleGoodsHavle: function(){
              //这里只通过commit(mutations中的方法,传递的参数)事件改变数据的状态
                this.$store.commit('goodsPriceHalve')
          }
      }
   }
</script>

效果图

提交方式二:提交载荷(Payload)(改变数据状态的同时传递参数)

参数:字符串/对象

这里修改商品名字。

store.js

    // 通过组件上的事件,通过this.$store.commit('mutations中的函数','需要从组件上传递给  mutation中这个函数的参数')
    mutations: {
        // 统一修改商品的名称;changeName(state,payload)参数1 state:数据源,参数2 payload:接收的参数
        changeName: (state,payload) => {
            var changeName = state.goodsList.map(currentValue => {
                return {
                    name: payload,//接收参数
                    price: currentValue.price/2
                }
            })
            state.goodsList = changeName;
        }
    }

这里的载荷payload可以是一个对象/字符串。

page6.vue

<template>
    <div>
        <h2>我是第四个页面</h2>
        <div>
            <input type="text" placeholder="请输入商品的新名字" v-model="inpValue">
            <button @click="changeGoodsName()">商品价格减半</button>
        </div>
        <router-link to='/page7'>action</router-link>
        <ul class="ul_list">
            <li v-for="item in goodsListHalv">
                <p class="name">商品:{{item.name}}</p>
                <p class="price">价格:¥{{item.price}}</p>
            </li>
        </ul>
    </div>
</template>
<script>
  export default {
     data() {
        return {
            inpValue:'',
        }
      },
      computed: {
          goodsListHalv(){
              return this.$store.state.goodsList;
          }
      },
      methods: {
        //   通过  click事件触发methods中的函数,进而改变store.js中数据的状态
          changeGoodsName: function(){
                // this.$store.commit('需要操作mutations中的函数名','从这个组件传递给第一个参数的参数')
                this.$store.commit('changeName',this.inpValue)
          }
      }
   }
</script>

这里的载荷payload就是输入框的值。

效果图

代码执行过程

上面的Mutation执行过程是:按钮点击–>执行组件中按钮点击事件方法–>执行$store.commit('vuex中mutatioms对象中对应的函数名',需要传递的参数)–>执行mutations里面对应的方法–>修改state里面对应的数据–>页面渲染。
Mutation 需遵守 Vue 的响应规则

既然 Vuexstore 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:
最好提前在你的 store 中初始化好所有所需属性。
当需要在对象上添加新属性时,你应该
使用 Vue.set(obj, 'newProp', 123), 或者
以新对象替换老对象。例如,利用 stage-3 的对象展开运算符我们可以这样写:

state.obj = { ...state.obj, newProp: 123 }

使用常量替代 Mutation 事件类型(更好的管理了事件的名称,使事件名称一目了然)

使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

 .vue

import { SOME_MUTATION } from './mutation-types'

this.$store.commit(SOME_MUTATION );

在组件中提交 Mutation

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

注入到methods中

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

// 直接this.incrementBy(params)使用

参考文献:链接

Logo

前往低代码交流专区

更多推荐