Vuex用來管理多個組件的共享狀態(tài)找岖。
適用場景:
1.多個視圖依賴于同一狀態(tài)
2.來自不同視圖的行為需要變更同一狀態(tài)
每個Vuex應(yīng)用的本質(zhì)是store(倉庫),包含應(yīng)用中大部分的狀態(tài)敛滋。
開始使用:
npm install vuex
import 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
num:1,
},
mutations:{
add(state){
state.num++;
};
},
}
})
1.state
就是定義狀態(tài)许布,Vue是單一狀態(tài)樹。便于管理
mapState輔助函數(shù):
當(dāng)一個組件需要獲取多個狀態(tài)的時候绎晃,將這些狀態(tài)都定義為計算屬性會有些重復(fù)和冗余蜜唾,可以使用mapState幫助生成計算屬性。
import {mapState} from 'Vuex'
//組件中使用:
computed: mapState([
"count";//映射this.count為state.count
])
computed: mapState({
countA: state => state.count,
countB: 'count',
//為了拿到this,需要用普通函數(shù)
countC(state){
return state.count + this.num
},
})
//相當(dāng)于:
computed:{
count=> this.store.state.count
}
對象展開運算符...
computed: {
...mapState(['count']),
num(){ return 123},
}
2.Getter
可以認(rèn)為是store 的計算屬性庶艾,會把值存儲起來袁余,當(dāng)依賴值發(fā)生改變才會重新計算。當(dāng)需要使用state派生出一些狀態(tài)時咱揍,我們可以用Getter做到颖榜。
mapGetter輔助函數(shù)用來將store的getter映射到局部計算屬性。
getters: {
fn: state => {
//對state進(jìn)行操作
}
}
//在組件中使用
import {mapGetter} from 'vuex'
export default{
computed: {
...mapGetter(["fn"])
}
}