上篇講到可以通過或者
this.$store.state.count
...mapState(['count'])
的方式可以拿到我們在state中存儲的count值,那麼如何修改這個值呢?
很多人都會想到this.$store.state.count++,但是這樣雖然可以達到目的,卻存在很大的隐患——多處修改卻無處溯源。
這節我們來認識一下mutations,學習正規操作公共資料的方式。
注:此篇文章案例續上篇
一、Mutation是用于變更Store中的資料。
- vuex隻能通過mutation變更Store資料,不可以直接操作Store中的資料。
- 通過mutation的這種方式雖然操作繁瑣了一點,但是卻可以集中監控所有資料的變化。
Vuex從入門到實戰(三)——使用Mutations變更state中的資料一、Mutation是用于變更Store中的資料。二、計數器執行個體——帶參+兩種方式觸發mutations - 觸發方式:
1. this.$store.commit('XXX')
2. import { mapMutations } from 'vuex'
----------------------------------
methods: {
// 2.将指定的mutations函數,映射為目前元件的methods函數
...mapMutations(['XXX'])
}
二、計數器執行個體——帶參+兩種方式觸發mutations
注:還是基于第一篇建立的vuex_demo1項目,本篇使用mutations實作加減一、加減N操作。
- 改動store/index.js——定義mutations
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// new一個Vuex執行個體并暴露出去
export default new Vuex.Store({
state: {
count: 0
},
// 1.mutations中第一個參數永遠都是自身的state,後面的參數都是形參
mutations: {
add (state) {
state.count++
},
// 2.第二個位置的step是我們傳遞的第一個參數,有其他參數還可以在後面加
addN (state, step) {
state.count += step
},
sub (state) {
state.count--
},
subN (state, step) {
state.count -= step
}
}
})
- 改動Addition元件——第一種方式:
觸發mutations$store.commit
<template>
<div>
<p>目前count的值為:{{ $store.state.count}}</p>
<button @click="handleAdd()">+1</button>
<button @click="handleAddN()">+N</button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
handleAdd () {
// commit的作用,就是調用某個mutations函數
this.$store.commit('add')
},
handleAddN () {
this.$store.commit('addN', 3)
}
}
}
</script>
- 改動Subtration元件——第二種方式:
觸發mutationsmapMutations
<template>
<div>
<p>目前count的值為:{{ count }}</p>
<button @click="handleSub()">-1</button>
<button @click="handleSubN()">-N</button>
</div>
</template>
<script>
// 1.從vuex中按需導入mapMutations
import { mapState, mapMutations } from 'vuex'
export default {
data () {
return {}
},
computed: {
...mapState(['count'])
},
methods: {
// 2.将指定的mutations函數,映射為目前元件的methods函數
...mapMutations(['sub', 'subN']),
handleSub () {
this.sub()
},
handleSubN () {
this.subN(3)
}
}
}
</script>
視訊位址:https://www.bilibili.com/video/BV1h7411N7bg?p=8