Vuex的概述
Vuex是什么
Vuex是實現(xiàn)組件全局狀態(tài)(數(shù)據(jù))管理的一種機(jī)制避诽,可以方便的實現(xiàn)組件之間數(shù)據(jù)的共享肄方。
image.png
Vuex的好處
- 能集中管理共享的數(shù)據(jù)稚矿,易于開發(fā)和后期維護(hù)
- 能高效地實現(xiàn)組件之間的數(shù)據(jù)共享掏熬,提高開發(fā)效率
- vuex中的數(shù)據(jù)是響應(yīng)式的搀崭,能實時保持?jǐn)?shù)據(jù)與頁面的同步
適用場景
只有組件間共享的數(shù)據(jù)叨粘,才有必要存儲到vux中;組件的私有數(shù)據(jù)存儲在自身data中即可
Vuex的基本使用
安裝vuex依賴包
npm install vuex --save
導(dǎo)入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
創(chuàng)建store對象
const store = new Vuex.Store({
// state中存放的就是全局共享的數(shù)據(jù)
state:{ count:0 }
})
將store對象掛載到vue實例中
new Vue({
el: '#app',
render: h => h(app),
router,
// 將創(chuàng)建的共享數(shù)據(jù)對象瘤睹,掛載到Vue實例中
// 所有組件升敲,就可以直接從store中獲取全局的數(shù)據(jù)
store
}
Vuex的核心概念
個人理解
image.png
State
State提供唯一的公共數(shù)據(jù)源,所有共享的數(shù)據(jù)都要統(tǒng)一放到Store的State中進(jìn)行存儲轰传。
const store = new Vuex.store({
state: { count: 0 }
})
訪問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 計算屬性
computed: {
...mapState(['count'])
//把 state 里的數(shù)據(jù)當(dāng)成組件數(shù)據(jù)使用
}
Mutation
Mutation用于變更Store中的數(shù)據(jù)
- 只能通過mutation變更Store數(shù)據(jù)驴党,不可以直接操作Store中的數(shù)據(jù)
- 通過這種方式雖然操作繁瑣,但是可以集中監(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ù)
如果通過異步操作更改數(shù)據(jù)获茬,必須通過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用于對Store中的數(shù)據(jù)進(jìn)行加工處理形成新的數(shù)據(jù)把还。
- Getter可以對Store中已有的數(shù)據(jù)加工處理之后形成新的數(shù)據(jù)吊履,類似Vue的計算屬性。
- Store中數(shù)據(jù)發(fā)生變化练俐,Getter的數(shù)據(jù)也會跟著變化冕臭。
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ù)使用
}