const store = new Vuex.Store({ state: { count: 1 }, mutations: { // 事件类型 type 为 increment increment (state) { // 变更状态 state.count++ } } })第一种使用方式:
// 方法 mutations:{ // 加的方法 increment(state,addcounter){ state.counter += addcounter }, // 减的方法 decrement(state,subcounter){ state.counter -= subcounter } },使用:
<template> <div> <h2>Vuex第四个页面 www.duidaima.com</h2> <button @click="addnum(5)">+</button> <button @click="subnum(5)">-</button> <p>{{$store.state.counter}}</p> </div> </template> <script> export default { name: "Vuexfour", methods:{ addnum(addcounter){ this.$store.commit("increment",addcounter) }, subnum(subcounter){ this.$store.commit("decrement",subcounter) } } } </script>
第二种方式 mapMutations
通过以函数映射的方式import {mapMutations} from 'vuex'通过刚才导入的mapMutations函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
methods:{ ...mapMutations(['add']) }示例:
<script> import { mapMutations } from 'vuex' export default { computed:{ count(){ return this.$store.state.count } }, methods:{ ...mapMutations([//采用解构的方式引入 'increment', 'decrement' ]) } } </script>