1、爲何要使用Vuex
一、多個組件依賴同一個狀態,使用組件之間通訊方法會很是繁瑣,例如多層嵌套組件。
二、須要全局保存的數據,例如用戶、權限信息,全局系統設置
2、Vuex的五個核心屬性
一、state:存儲狀態
const store = new Vuex.Store({
state: {
count: 0
}
});
$store.state.count
複製代碼
二、getters:state做爲第一個參數,其餘getters做第二個參數,返回值會根據他的依賴緩存起來,至關於Vue的計算屬性
const store = new Vuex.Store({
state: {
count: 1,
sum: 2
},
getters: {
getCountAndSum: (state,getters) => {
return state.count + state.sum;
}
}
});
$store.getters.getCountAndSum
複製代碼
三、mutations:修改狀態(同步的),state 做爲第一個參數,提交載荷做爲第二個參數
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state, obj) {
state.count += obj.n;
}
}
});
$store.commit('increment', {n: 100});
複製代碼
四、actions:異步操做(執行mutations的方法,不是直變動狀態)
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state, obj) {
state.count += obj.n;
}
},
actions: {
increment (context) {
context.commit('increment');
}
}
});
$store.dispatch('increment');
複製代碼
五、modules:store的子模塊
const a = {
state: {
count: 0
},
getters: {
getCount2 (state, getters, rootState) {
return state.count + 2;
}
},
mutations: {
increment (state, getters, rootState) {
state.count++;
}
},
actions: {
increment (context) {
// context.state.count;
// context.rootState.count;
context.commit('increment');
}
}
};
const b = {};
const store = new Vuex.Store({
modules: {
a,
b
}
});
// 其餘組件調用 (獲取state的變量須要加上引入的module的別名)
$store.state.a
$store.state.b
複製代碼
3、Vuex輔助函數
<template>
<div class="about">
<h1>count: <span>{{count}}</span></h1>
<h1>getCount: <span>{{$store.getters.getCount}}</span></h1>
<h1>sum: <span>{{sum}}</span></h1>
<h1>getSum: <span>{{$store.getters.getSum}}</span></h1>
<button @click="clickB">test
</button>
</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex';
export default {
name: 'about',
data () {
return {
count: 0,
sum: 0
}
},
computed: {
...mapState({
count: state => state.count,
countAlias: 'count',
countPlusLocalState (state) {
return state.count + this.localCount;
}
}),
...mapGetters([
'getCount', 'getSum'
])
},
mounted () {
this.count = this.$store.state.count;
this.sum = this.$store.state.a.sum;
},
methods:{
...mapMutations(
'add','addO'
),
...mapActions([
'add','addO'
]),
clickB () {
this.$store.dispatch('add');
this.$store.dispatch('addO');
}
}
}
</script>
複製代碼