1.1 組件之間共享數據的方式
- 父向子傳值: v-bind屬性綁定
- 子向父傳值: v-on 事件綁定
- 兄弟組件之間共享數據: EventBus
- $on 接受數據的那個組件
- $emit 發送數據的那個組件
1.2 Vuex是什麼
Vuex 是實現組件全局狀態(數據)管理的一種機制,可以方便的實現組件之間數據的共享。
通俗來說就是在組件的旁邊定義一個共享的數據狀態對象(store)
1.3 使用Vuex統一管理狀態的好處
- 能夠在Vuex中集中管理共享的數據,易於開發和後期維護
- 能夠高效的實現組件之間的數據共享,提高開發效率
- 存儲在vuex中的數據都是響應式的,能夠實時保持數據與頁面的同步
1.4 什麼樣的數據適合存儲到Vuex中
一般情況下,只有組件之間共享的數據,纔有必要存儲的Vuex中;對於組件中的私有數據,依舊存儲在組件的自身的data中即可。
把所有數據放在vuex也是可以的,看實際需要
2. Vuex 的核心概念
2.1 核心概念概述
Vuex中的主要核心概念如下:
- State
- Mutation
- Action
- Getter
2.2 State
State 提供唯一的公共數據源,所有共享的數據都要統一放到Store的State中進行存儲
//創建store數據源,提供唯一公共數據
const store = new Vuex.Store({
state:{count:0}
})
> 組件中訪問State中數據的第一種方式
this.$store.state.全局數據名稱`
> 組件中訪問State中數據的第二種方式
>`//1.從vuex中按需導入mapState 函數
import {mapState} from 'vuex'
//2. 通過剛纔導入的mapState函數,將當前組件需要的全局數據,映射爲當前組件的computed計算屬性
computed:{
...mapState(['count])
}
不允許組件內直接修改全局的store的數據
2.3 Mutation
Mutation用於變更Store中的數據
- 只能通過mutation變更Store數據,不可以直接操作Store中的數據
- 通過這種方式雖然操作起來繁瑣,但是可以集中監控所有數據的變化
// 定義mutation
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
// 變更狀態
state.count++
}
}
})
// 觸發mutation
methods:{
handles(){
this.$store.commit('add')
}
}
可以在觸發mutation時傳遞參數
//定義mutation
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
addN(state.step){
//變更狀態
state.count+=step
}
}
})
//觸發mutation
methods:{
handle2(){
//調用commit函數
//觸發mutations時攜帶參數
this.$store.commit('addN',3)
}
}
觸發mutations的第二種方式
this.$store.commit() 是觸發mutations的第一種方式,觸發mutations的第二種方式:
//1. 從vuex中按需導入mapMutations函數
import {mapMutations} from 'vuex
通過剛纔導入的mapMutations函數,將需要的mutations函數,映射爲當前組件的methods方法
// 2. 將指定的mutations函數,映射爲當前組件的methos函數
methods:{
...mapMutations(['add','addN'])
}
2.4 Action
Action 用於傳處理異步任務
如果通過異步操作變更數據,必須通過Action,而不能使用Mutation,但是在Action中還是要通過觸發Mutation的方式間接變更數據
//定義Action
const store = new Vuex.Store({
//...
mutations:{
add(state){
state.count++
}
},
actions:{
addAsync(context){
setTimeout(()=>{
context.commit('add)
},1000)
}
}
})
//觸發Action
methods:{
handle(){
//觸發actions的第一種方法
this.$store.dispatch('addAsync')
}
}
import {mapAction} from 'vuex'
觸發actions異步任務時攜帶參數
// 定義Action
const store = new Vuex.Store({
mutations:{
addN(state,step){
state.count+=step
}
},
actions:{
addNAsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
}
})
//觸發Action
methods:{
handle(){
//在調用dispatch函數
// 觸發actions時攜帶參數
this.$store.dispatch('addNAsync',5)
}
}
`
觸發actions的第二種方法
第一種是this.$store.dispatch()是觸發actions的第一種方式
// 1. 從vuex中按需導入mapActions函數
import {mapActions} from 'vuex
//2. 將指定的actions函數,映射爲當前組件的methods函數
methods:{
...mapActions(['addAsync','addAsync'])
}
2.5 Getter
Getter 用於對Store中的數據進行加工處理形成新的數據
- Getter 可以對Store中已有的數據加工處理之後形成新的數據,類似Vue的計算屬性
- Store中數據發生變化,Getter的數據也會跟着變化
//定義Getter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state=>{
return '當前最新的數量是【'+state.count+'】'
}
}
})
>//使用getters 第一種方式
this.$store.getters.名稱
//使用第二種
import {mapGetters}from 'vuex'
computed:{
...mapGetters(['showNum'])
}