Vuex的概述
Vuex是什么
Vuex是實(shí)現(xiàn)組件全局狀態(tài)(數(shù)據(jù))管理的一種機(jī)制,可以方便的實(shí)現(xiàn)組件之間數(shù)據(jù)的共享。

image.png
Vuex的好處
- 能集中管理共享的數(shù)據(jù),易于開發(fā)和后期維護(hù)
- 能高效地實(shí)現(xiàn)組件之間的數(shù)據(jù)共享,提高開發(fā)效率
- vuex中的數(shù)據(jù)是響應(yīng)式的,能實(shí)時(shí)保持?jǐn)?shù)據(jù)與頁(yè)面的同步
適用場(chǎng)景
只有組件間共享的數(shù)據(jù),才有必要存儲(chǔ)到vux中;組件的私有數(shù)據(jù)存儲(chǔ)在自身data中即可
Vuex的基本使用
安裝vuex依賴包
npm install vuex --save
導(dǎo)入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
創(chuàng)建store對(duì)象
const store = new Vuex.Store({
// state中存放的就是全局共享的數(shù)據(jù)
state:{ count:0 }
})
將store對(duì)象掛載到vue實(shí)例中
new Vue({
el: '#app',
render: h => h(app),
router,
// 將創(chuàng)建的共享數(shù)據(jù)對(duì)象,掛載到Vue實(shí)例中
// 所有組件,就可以直接從store中獲取全局的數(shù)據(jù)
store
}
Vuex的核心概念
個(gè)人理解

image.png
State
State提供唯一的公共數(shù)據(jù)源,所有共享的數(shù)據(jù)都要統(tǒng)一放到Store的State中進(jìn)行存儲(chǔ)。
const store = new Vuex.store({
state: { count: 0 }
})
訪問(wèn)State
第一種方式
this.$store.state.全局?jǐn)?shù)據(jù)名稱
第二種方式
// 1.從vuex中導(dǎo)入 mapState 函數(shù)
import { mapState } from 'vuex'
// 2.將需要的全局?jǐn)?shù)據(jù)映射為當(dāng)前組件的 computed 計(jì)算屬性
computed: {
...mapState(['count'])
//把 state 里的數(shù)據(jù)當(dāng)成組件數(shù)據(jù)使用
}
Mutation
Mutation用于變更Store中的數(shù)據(jù)
- 只能通過(guò)mutation變更Store數(shù)據(jù),不可以直接操作Store中的數(shù)據(jù)
- 通過(guò)這種方式雖然操作繁瑣,但是可以集中監(jiān)控所有數(shù)據(jù)的變化
const store = new Vuex.store({
state: { count: 0 },
mutations: {
add(state) {
// 變更狀態(tài)
state.count ++
}
}
})
觸發(fā)Mutation(commit)
第一種方式
this.$store.commit('add')
第二種方式
// 1.從vuex中導(dǎo)入 mapMutations 函數(shù)
import { mapMutations} from 'vuex'
// 2.將指定的 mutations 函數(shù)映射為當(dāng)前組件的 methods 函數(shù)
methods: {
...mapMutations(['add','addN'])
//把 mutations 里的函數(shù)當(dāng)成組件函數(shù)使用
}
Action
Action用于處理異步任務(wù)
如果通過(guò)異步操作更改數(shù)據(jù),必須通過(guò)Action,而不能直接用Mutation;是在Action中觸發(fā)Mutation間接更改。
const store = new Vuex.store({
state: { count: 0 },
mutations: {
...
},
actions: {
addAsync(context) {
setTimeOut(() => {
context.commit('add')
},1000)
}
}
})
觸發(fā)Action(dispatch)
第一種方式
this.$store.dispatch('addAsync')
第二種方式
// 1.從vuex中導(dǎo)入 mapActions 函數(shù)
import { mapActions } from 'vuex'
// 2.將指定的 actions 函數(shù)映射為當(dāng)前組件的 methods 函數(shù)
methods: {
...mapActions(['addAsync','addNAsync'])
//把 actions 里的函數(shù)當(dāng)成組件函數(shù)使用
}
Getter
Getter用于對(duì)Store中的數(shù)據(jù)進(jìn)行加工處理形成新的數(shù)據(jù)。
- Getter可以對(duì)Store中已有的數(shù)據(jù)加工處理之后形成新的數(shù)據(jù),類似Vue的計(jì)算屬性。
- Store中數(shù)據(jù)發(fā)生變化,Getter的數(shù)據(jù)也會(huì)跟著變化。
const store = new Vuex.store({
state: { count: 0 },
mutations: {
...
},
actions: {
...
},
getters: {
showNum: state => {
return '數(shù)量是:' + state.count
}
}
})
使用Getter
第一種方式
this.$store.getters.名稱
第二種方式
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
//把 getters 里的數(shù)據(jù)當(dāng)成組件數(shù)據(jù)使用
}