上次分享回顧
父子組件的通信
- 父 -> 子: props
- 子 -> 父: 自定義event
- 組件文檔化
Vuex起步
Vuex主要應(yīng)用于中算柳、大型單頁應(yīng)用的數(shù)據(jù)狀態(tài)管理架構(gòu)押袍。
為什么要數(shù)據(jù)狀態(tài)管理?
- 組件數(shù)據(jù)共享
組件之間如何數(shù)據(jù)共享(組件通信)
- 父 -> 子:props
- 子 -> 父:自定義event
- 兄弟之間侧巨?其他非父子? :自定義event稠集?
可能的解法
-
自定義event
var bus = new Vue() // in component A's method bus.$emit('id-selected', 1) // in component B's created hook bus.$on('id-selected', function(id){ //... })
-
共享數(shù)據(jù)源
const srcData = { count: 0 } const vmA = new Vue({ data: srcData }) const vmB = new Vue({ data: srcData })
存在的問題
- 誰在emit事件?誰在on事件微峰?父組件和子組件強(qiáng)耦合
- 如何追蹤數(shù)據(jù)的狀態(tài)變化?
- 業(yè)務(wù)邏輯遍布各個(gè)組件抒钱,導(dǎo)致各種意想不到的問題
Vuex基本概念
- state
- 狀態(tài)的容器
- getters
- 狀態(tài)的獲取函數(shù)
- mutations
- 修改狀態(tài)的事件回調(diào)函數(shù)
- actions
- 分發(fā)修改狀態(tài)的事件
const store = new Vuex.Store({
//state
state: {
count: 0
},
//mutations
mutations: {
INIT (state, data) {
state.count = data.count
},
INCREASE (state) {
state.count++
},
DECREASE (state) {
state.count--
}
},
//getters
getters: {
getCount (state) {
return state.count
}
},
//actions
actions: {
init(context){
context.commit('INIT', {
count: 10
})
},
inc(context){
context.commit('INCREASE')
},
dec(context){
context.commit('DECREASE')
}
}
})
Vuex基本理解
- 數(shù)據(jù)的集合其中處理(DB)
- 數(shù)據(jù)的操作集中處理 (CRUD)
- 所有對(duì)數(shù)據(jù)的操作(CRUD)以請求(commit)的方式提交處理 (DAO)