Vue-CLI 3.0集成Vuex,默認文件爲store.js
內容:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vue.Store({
*****
})
官方文檔中的五個狀態:
1.State
單一狀態樹,簡單來說就是定義初始值的位置。
state:{
*****
}
全局獲取方法:this.$store.state.***
2.Getter
類似計算屬性(實時監聽),帶有更新狀態,獲取更新後的最新狀態值。
全局獲取方法:this.$store.getters.***
getters:{
***(state){ //函數名自定
return state.*** //state.*** => 想要監聽的值
}
}
3.Mutation
更改store中狀態的唯一方法,提交mutation
定義:
mutations:{
***(state){ //函數名自定
//值(狀態)的變更
state.*** = *** //要改變的狀態
}
}
全局調用:
this.$store.commite(' *** ') // 觸發一個類型爲***的mutation
還可以傳入額外參數(提交載荷):
mutations:{
***(state,n){ //函數名自定
state.*** += n //任意操作
}
}
調用:
this.$store.commit('***',n的值)
大多數情況,傳入的應該是一個對象,好處:易讀
例如文檔的例子:
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
//全局調用
this.$store.commit('increment', {
amount: 10
})
需要注意的是:muntation必須是同步函數
4.Action
寫法:將mutation中想要進行異步操作的方法包裹在內
特點:提交mutation,支持異步操作(任意)
//定義
mutations:{
increment(state){
state.count++
}
},
actions:{
increment(context){
context.commit('increment')
}
}
//調用:
this.$store.dispatch('increment')
異步:
actions: {
incrementAsync ({ commit }) { //解構寫法
setTimeout(() => {
commit('increment')
}, 1000)
}
}
另:同樣支持傳值(載荷)
5.Model
允許將store分爲模塊:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態
如果不重定命名空間,公共調用同上,待深入