先來看看我們常規使用 vuex 的步驟:
// store.js 定義
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increase(state) {
state.count++
}
}
})
export default store
其他組件取值的時候:
<div class="app">{{this.$store.state.count}}</div>
或者這樣:
<template>
<div class="app">{{ count }}</div>
</template>
<script>
export default {
name: "xxx",
computed: {
count() {
return this.$store.state.count
}
}
}
</script>
一定覺得很熟悉吧?但上面這種取值方式在字段很多的時候會顯得亂。下面我們來看看使用輔助函數的方式:
(前排說明):
mapState 與 mapGetters 要放在計算屬性 computed 中
mapMutations 與 mapActions 要放在 methods 中
mapState 輔助函數
<div class="app">{{ count }}---------{{ other }}</div>
<script>
import mapState from 'vuex'
export default {
name: 'xxx',
computed: mapState(['count', 'other']) // 想取哪個值就寫哪個字段
}
</script>
上面這段代碼就等同於:
<div class="app">{{ count }}---------{{ other }}</div>
computed: {
count() {
return this.$store.state.count
}
other() {
return this.$store.state.other
}
}
還有一種方式,當我們需要自定義其他計算屬性的時候使用:
<div class="app">{{ count }}---{{custom}}---{{ other }}</div>
computed: {
// ...是es6中的展開運算符,會把類似 (4) [1, 2, 3, 4] 輸出成 1 2 3 4
...mapState(['count', 'other'])
custom() {
return 1234
}
}
mapGetters 輔助函數
getters 相當於 Vue 中的計算屬性,通過 getters 進一步處理,得到我們想要的值 ,而且允許傳入參數,第一個參數就是 state
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0,
price: 1,
},
getters: {
sum(state) {
return state.count * state.price
},
increase(state) {
return state.count++
}
},
mutations,
actions,
modules,
})
組件中使用:
<div class="app">{{ sum }}---{{ increase }}---{{ custom}}</div>
computed: {
...mapGetters(['sum', 'increase'])
custom() {
return 1234
}
}
mapMutations 輔助函數
mutaions的主要作用就是爲了修改 state,用法與 mapState、mapGetters 類似
<div class="app" @click="increase">點擊增加</div>
methods: {
...mapMutations(['increase'])
}
上面代碼相當於平常我們寫的:
<div class="app" @click="handleClick({step: 2})">點擊增加</div>
methods: {
handleClick(payload) {
this.$store.commit('increase', payload })
}
}
擴展:
通常,我們使用常量來替代 mutations 事件類型:
// mutations_types.js 中定義
export const INCREASE_COUNT = 'INCREASE_COUNT'
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import { INCREASE_COUNT } from './mutations_types.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0,
},
mutations: {
[INCREASE_COUNT](state, payload) {
state.count += payload.step
}
},
actions,
modules,
})
mapActions 輔助函數
actions 類似於 mutaion,區別是 actions 可以提交 mutation
actions 不要直接去操作 state,而是去操作 mutation
actions 中可以包含異步操作,mutation 不可以
// actions.js
import { getUser} from 'xxx'
import { GET_USER_INFO} from './mutation_types.js'
async getUserInfo({ commit, state }) {
let res = await getUser();
commit(GET_USER_INFO, res)
},
在組件中使用:
mounted() {
this.getUserInfo();
},
methods: {
...mapActions(['getUserInfo'])
}
相當於平常我們寫的:
mounted() {
this.getUserInfo();
},
methods: {
getUserInfo() {
return this.$store.dispatch('getUserInfo')
}
}
好了,大概就這樣了,如有理解錯誤,還望指出