4

VUEX 使用学习三 : mutations - 香吧香

 1 year ago
source link: https://www.cnblogs.com/zjdxr-up/p/17056787.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

转载请注明出处:

  在 Vuex 中 store 数据改变的唯一方法就是提交 mutationsmutations里面装着一些改变数据方法的集合,这是Vuex 设计很重要的一点,就是把处理数据逻辑方法全部放在 mutations 里面,使得数据和视图分离。

  通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
     // 事件类型 type 为 increment
    increment (state) { 
      // 变更状态
      state.count++
    }
  }
})

第一种使用方式:

  this.$store.commit() 是触发mutations的第一种方式,

// 方法
mutations:{
  // 加的方法
  increment(state,addcounter){
    state.counter += addcounter
  },
  // 减的方法
  decrement(state,subcounter){
    state.counter -= subcounter
  }
},
<template>
  <div>
    <h2>Vuex第四个页面</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

  通过以函数映射的方式

    1.从vuex中按需求导入mapMutations 函数

import {mapMutations} from 'vuex'

    通过刚才导入的mapMutations函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性

    2. 将指定的mutations函数,映射为当前组件的methods函数

methods:{ ...mapMutations(['add']) }
<script>
import { mapMutations } from 'vuex'
export default {
  computed:{
    count(){
      return this.$store.state.count
    }
  },
  methods:{
    ...mapMutations([//采用解构的方式引入
      'increment',
      'decrement'
    ])
  }
}
</script>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK