vuex基礎用例
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count:0
},
const mutations = {
add(state){
state.count++
},
dcre(state){
state.count--
},
}
const actions = {
add:({ commit }) => {
commit("add")
},
dcre:({ commit }) => {
commit("dcre")
}
},
export default new Vuex.Store({
state,
mutations,
actions
});
關於actions:
官方文檔是這麼寫的:
Action 類似於 mutation,不同在於:
Action 提交的是 mutation,而不是直接變更狀態。
Action 可以包含任意異步操作。
然後在組件中導入, 通過Action觸發add、dcre方法
<template>
<div>
{{ $store.state.count }}
<button @click="add">增加</button>
<button @click="drce">刪減</button>
</div>
</template>
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'add:
'dcre',
// `mapActions` 也支持載荷:
' dcre' // 將 `this. dcre(amount)` 映射爲 `this.$store.dispatch(' dcre', amount)`
]),
...mapActions({
add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')`
})
}
}
vuex多業務模塊用例
多業務模塊時,不同模塊間數據並不相干,將前臺state拆成多個module方便代碼維護;通過這種思想使各功能模塊高內聚低耦合
舉個例子:
1.創建store文件 》module文件(放置不同數據塊)、index.js
2.module文件 放置a.js、b.js
index.js入口文件導入數據塊a,b
3.在main.js入口文件裏修改 store默認導入路徑,修改如下
4.最後在組件中引入數據