Vuex是什么?
Vuex是Vue配套的公共數(shù)據(jù)管理工具,我們可以將共享的數(shù)據(jù)保存到Vuex中,方便項目中的任何組件獲取和修改vuex中的數(shù)據(jù)。
為什么要使用Vuex?
在企業(yè)開發(fā)中,我們遇到兩個問題:
1、如果想要在子組件中使用祖先組件的數(shù)據(jù),只能一級一級的往下傳遞,很麻煩!
2、兄弟組件間不能直接傳遞數(shù)據(jù),若兄弟組件間想要傳遞數(shù)據(jù),只能借助父組件!
解決方法:使用Vuex
Vuex共享數(shù)據(jù):
在Vuex中:
1、State 屬性是 Vuex 這一狀態(tài)管理工具的唯一的數(shù)據(jù)源,所有的共享數(shù)據(jù)都儲存在里面( 類似data)。
2、mutation屬性 是 Vuex 中改變 state 唯一的方法。
mutation的使用與事件處理函數(shù)非常相似,都具有類型和回調(diào)函數(shù)(類似methods,不過獲取state中的變量不是this.變量名,而是state.變量名)。
3、getters屬性類似組件中的計算屬性(computed),當數(shù)據(jù)被調(diào)用過且沒發(fā)生改變時,之后的調(diào)用就到緩存區(qū)中找。
使用getters中的數(shù)據(jù):this.$store.gettters.方法名
在組件中:
1、先在祖先組件中保存共享數(shù)據(jù)(后代組件可直接使用): store:store
2、使用共享: this.$store.state.數(shù)據(jù)名
3、調(diào)用Vuex的mutations中的函數(shù)修改共享:this.$store.commit('方法名')
4、 使用getters中的數(shù)據(jù):this.$store.getters.方法名
e.g.
export default new Vuex.Store({
state: { // 保存共享數(shù)據(jù),類似data
count: 0
},
mutations: { // 保存修改共享數(shù)據(jù)的方法 ,類似methods
decrement (state) {
state.count--
},
increment (state) {
state.count++
}
},
getters:{//類似計算屬性computed
fn (state) {
return state.count+"拼接內(nèi)容"
}
}
})
在組件中:
<template>
<div class="about">
<button @click="mAdd">增加</button>
<button @click="mSub">減少</button>
//2、使用共享數(shù)據(jù) this.$store.state.數(shù)據(jù)名
<span>{{this.$store.state.msg}}</span>
//使用getters:this.$store.getters.方法名
<span>{{this.$store.getters.fn}}</span>
</div>
</template>
export default {
data () {
return {
count: 1
}
},
//1、先在祖先組件中保存共享數(shù)據(jù),后代組件可直接使用
store:store,
methods:{
mAdd (){
//調(diào)用Vuex的mutations中的函數(shù)修改共享數(shù)據(jù)
this.$store.commit("increment");
},
mSub () {
this.$store.commit("decrement");
}
}
}