Vue使用Vuex一步步封装并使用store
文章目錄
- 一、安裝Vuex依賴
- 二、一步步封裝store
- 1. main.js中全局引入store倉(cāng)庫(kù)(下一步創(chuàng)建)
- 2. this.$store
- 3. this.$store.state
- 4. this.$store.getters(this. $store.state的升級(jí))
- 5. this.$store.commit('mutations')
- 6. this.$store.dispatch('actions')(this. $store.commit('mutations')的升級(jí))
- 7.strict嚴(yán)格模式
- 三、modules 模塊化
- 四、使用倉(cāng)庫(kù)
- 1、無map系列
- 2、map映射系列
- 3、總結(jié)
精簡(jiǎn)版
一、安裝Vuex依賴
cnpm install vuex --save二、一步步封裝store
1. main.js中全局引入store倉(cāng)庫(kù)(下一步創(chuàng)建)
import store from './store' //引入storenew Vue({el: '#app',router,store, //掛載store,this將自動(dòng)生成$store屬性template: '<App/>',components: { App } })掛載store,this將自動(dòng)生成$store屬性
2. this.$store
創(chuàng)建store倉(cāng)庫(kù):習(xí)慣在src下創(chuàng)建store文件夾,再創(chuàng)建index.js,內(nèi)容:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store();export default store;此時(shí)你已經(jīng)有了一個(gè)空的store全局倉(cāng)庫(kù),沒有任何功能,但可以在任何vue實(shí)例下使用 this.$store 去訪問它。
- store使用范圍均是可以全局使用;
- let a=1; {a:a}.a 的縮寫是 {a}.a,即當(dāng)字典的鍵和值命名一樣時(shí),可以省略只寫a
- state、getters、mutations、mutations均是Vuex封裝好的特殊變量,以下聲明的功能變量均是這些名字,一個(gè)好處是store掛載該功能時(shí)可以簡(jiǎn)寫(如3-1,本例均如此)。當(dāng)然你也可直接在store中寫功能(如3-2)。
3. this.$store.state
給store倉(cāng)庫(kù)讀取數(shù)據(jù)功能:state
/********* 3-1 **********/ import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設(shè)置的全局訪問的state對(duì)象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const store = new Vuex.Store({state});export default store;此時(shí)你的store倉(cāng)庫(kù)已經(jīng)有了存取數(shù)據(jù)的功能,可以用 this.$store.state.themeColor 等數(shù)據(jù)了。
下面是第二種寫法
4. this.$store.getters(this. $store.state的升級(jí))
給state功能升級(jí),讓他擁有計(jì)算能力(類似vue中的computed方法):getters:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設(shè)置的全局訪問的state對(duì)象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實(shí)時(shí)監(jiān)聽state值的變化(最新狀態(tài))getThemeColor(state) { //定義函數(shù),返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const store = new Vuex.Store({state, // 掛載存取數(shù)據(jù)功能getters //掛載數(shù)據(jù)計(jì)算功能 }); export default store;此時(shí)使用 this.$store.getters.getThemeColor 獲取顏色,將自動(dòng)根據(jù)時(shí)間的不同自動(dòng)設(shè)置主題是否有透明的效果
5. this.$store.commit(‘mutations’)
給store倉(cāng)庫(kù)使用函數(shù)功能(只為操作state數(shù)據(jù)):mutations - 同步
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設(shè)置的全局訪問的state對(duì)象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實(shí)時(shí)監(jiān)聽state值的變化(最新狀態(tài))getThemeColor(state) { //定義函數(shù),返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const mutations = {//自定義改變state初始值的方法,這里面的參數(shù)除了state之外還可以再傳額外的參數(shù)(變量或?qū)ο?;clearCatch(state) { state.cache = "";state.changeThemeCount= 0;},setThemeColor(state,color,opacity){ state.themeColor.val = color;state.themeColor.opacity = opacity;state.changeThemeCount++;} }; const store = new Vuex.Store({state, // 掛載存取數(shù)據(jù)功能getters, //掛載數(shù)據(jù)計(jì)算功能mutations // 掛載函數(shù)功能 }); export default store;此時(shí)可以使用 this.$store.commit(‘setThemeColor’,‘grey’,‘1’) 了(注意第一個(gè)參數(shù)是函數(shù)名,不是傳參給state的,state自己會(huì)傳,后兩個(gè)才是對(duì)應(yīng)傳參)。可以主動(dòng)設(shè)置主題色和透明度,操作是同步的,即如果你在同一個(gè)組件連續(xù)調(diào)用多次setThemeColor函數(shù),獲取倉(cāng)庫(kù)中state.changeThemeCount的值是一樣的,下面介紹異步函數(shù)。
6. this.$store.dispatch(‘a(chǎn)ctions’)(this. $store.commit(‘mutations’)的升級(jí))
給store倉(cāng)庫(kù)的函數(shù)commit功能升級(jí)(只為異步操作mutations中的函數(shù)):actions - 異步
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設(shè)置的全局訪問的state對(duì)象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實(shí)時(shí)監(jiān)聽state值的變化(最新狀態(tài))getThemeColor(state) { //定義函數(shù),返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const mutations = {//自定義改變state初始值的方法,這里面的參數(shù)除了state之外還可以再傳額外的參數(shù)(變量或?qū)ο?;clearCatch(state) { state.cache = "";state.changeThemeCount= 0;},setThemeColor(state,color,opacity){ state.themeColor.val = color;state.themeColor.opacity = opacity;state.changeThemeCount++;} }; const actions = {//自定義觸發(fā)mutations里函數(shù)的方法,context與store 實(shí)例具有相同方法和屬性setThemeColorAction(context,color,opacity){context.commit('setThemeColor',color,opacity);} }; const store = new Vuex.Store({state, // 掛載存取數(shù)據(jù)功能getters, //掛載數(shù)據(jù)計(jì)算功能mutations, // 掛載函數(shù)功能actions, // 掛載異步函數(shù) }); export default store;此時(shí)可以使用 this.$store.dispatch(‘setThemeColorAction’,‘grey’,‘1’) 了(注意第一個(gè)參數(shù)是函數(shù)名,不是傳參給context的,context自己會(huì)傳,后兩個(gè)才是對(duì)應(yīng)傳參)。可以主動(dòng)設(shè)置主題色和透明度,操作是異步的,即如果你在同一個(gè)組件連續(xù)調(diào)用多次setThemeColorAction函數(shù),獲取倉(cāng)庫(kù)中state.changeThemeCount的值就不是一樣的。
7.strict嚴(yán)格模式
export default new Vuex.Store({strict: true,state: {...},... }此模式下所有的狀態(tài)變更(即更新state)必須使用mutation(commit),如果在組件中直接修改state則會(huì)報(bào)錯(cuò)。這樣的好處是所有的state的更新都體現(xiàn)在倉(cāng)庫(kù)中,整改方便;使用devTools調(diào)試工具時(shí)可以跟蹤到狀態(tài)的修改。
三、modules 模塊化
第二個(gè)模塊介紹了store倉(cāng)庫(kù)的四個(gè)功能:state、getters、mutations和actions,下面介紹第五個(gè)功能:modules。
- 當(dāng)項(xiàng)目比較大時(shí),一個(gè)store中數(shù)據(jù)會(huì)非常多而復(fù)雜,不易管理。此時(shí)便可建多個(gè)“子倉(cāng)庫(kù)”,分別對(duì)應(yīng)不同模塊做數(shù)據(jù)的讀取和操作。
- 注意主倉(cāng)庫(kù)還是那一個(gè),只要把他的“子倉(cāng)庫(kù)”放在主倉(cāng)庫(kù)的modules下即可。
- 子倉(cāng)庫(kù)看著很像倉(cāng)庫(kù),其實(shí)它并不是store的實(shí)例,不是倉(cāng)庫(kù)(new Vuex.Store()實(shí)例化后的對(duì)象才是倉(cāng)庫(kù)),只是一個(gè)普通js對(duì)象(字典)。
1、在store下新建modules文件夾,在modules下新建home.js“子倉(cāng)庫(kù)”。
即home.js只管主頁(yè)下的數(shù)據(jù)(一般不要分的太細(xì),最多一個(gè)頁(yè)面一個(gè)倉(cāng)庫(kù)管簡(jiǎn)潔),下面是home.js代碼
2.“子倉(cāng)庫(kù)”創(chuàng)建完成,要讓主倉(cāng)庫(kù)引用它:
import Vue from 'vue'; import Vuex from 'vuex'; import home from './modules/home.js'Vue.use(Vuex);const state={ //要設(shè)置的全局訪問的state對(duì)象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實(shí)時(shí)監(jiān)聽state值的變化(最新狀態(tài))getThemeColor(state) { //定義函數(shù),返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const mutations = {//自定義改變state初始值的方法,這里面的參數(shù)除了state之外還可以再傳額外的參數(shù)(變量或?qū)ο?;clearCatch(state) { state.cache = "";state.changeThemeCount= 0;},setThemeColor(state,color,opacity){ state.themeColor.val = color;state.themeColor.opacity = opacity;state.changeThemeCount++;} }; const actions = {//自定義觸發(fā)mutations里函數(shù)的方法,context與store 實(shí)例具有相同方法和屬性setThemeColorAction(context,color,opacity){context.commit('setThemeColor',color,opacity);} }; const store = new Vuex.Store({state, // 掛載存取數(shù)據(jù)功能getters, //掛載數(shù)據(jù)計(jì)算功能mutations, // 掛載函數(shù)功能actions, // 掛載異步函數(shù)modules:{ // 掛載子倉(cāng)庫(kù)home} }); export default store;此時(shí)便有了第一個(gè)“子倉(cāng)庫(kù)”了!
四、使用倉(cāng)庫(kù)
1、無map系列
適合使用場(chǎng)景較少:
建好倉(cāng)庫(kù),組件中直接使用state、getters、mutations、actions:
- this.$store.state.*
- this.$store.getters.*
- this.$store.commit.*
- this.$store.dispatch.*
2、map映射系列
適合使用場(chǎng)景頻繁:
1、使用mapGetters、mapActions 和 mapStates之前需要import導(dǎo)入:
2、使用ES6新語(yǔ)法-超引用,將某個(gè)功能下的數(shù)據(jù)或方法全部映射出來以供使用,下面是mapState、mapGetters、mapActions的例子:
//這里的...是超引用,映射內(nèi)容,可以寫在computed下、methods下等(一般放在開頭)// 直接從庫(kù)中取值 - 將庫(kù)里的users值返回給字典中的users并映射給this組件...mapState({ users:state=>state.home.users }),// 使用計(jì)算屬性 - 將庫(kù)里的users計(jì)算后的值返回給字典中的users并映射給this組件...mapGetters('home',{ users:'getUsers' //獲取清理后的數(shù)據(jù)//由于home倉(cāng)庫(kù) namespaced:true,所以第一個(gè)參數(shù)作為標(biāo)識(shí)// 不使用標(biāo)識(shí)訪問的是主倉(cāng)庫(kù)})// 使用異步函數(shù) - 以數(shù)組中的函數(shù)名,從庫(kù)中對(duì)應(yīng)的函數(shù)映射給this組件以供使用...mapActions('home',['invokeAddUser'])// 有某個(gè)組件 <span @click='invokeAddUser(name)'></span>// 或者直接使用 this.invokeAddUser(name)3、擴(kuò)展
1、mapState映射的三種寫法computed: mapState({// 箭頭函數(shù)可使代碼更簡(jiǎn)練count: state => state.count,// 傳字符串參數(shù) 'count' 等同于 `state => state.count`countAlias: 'count',// 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)countPlusLocalState (state) {return state.count + this.localCount}})2、當(dāng)映射的計(jì)算屬性的名稱與state的子節(jié)點(diǎn)名稱相同時(shí),我們也可以給 mapState傳一個(gè)字符串?dāng)?shù)組。computed: mapState([ // 數(shù)組"count"])3、倉(cāng)庫(kù)中action的第二種接收參數(shù) const actions = {//自定義觸發(fā)mutations里函數(shù)的方法,{commit}與store 實(shí)例具有相同方法和屬性setThemeColorAction({commit},color,opacity){commit('setThemeColor',color,opacity);} };3、總結(jié)
1、Vuex 是一個(gè)專門為 Vue.js 應(yīng)用所設(shè)計(jì)的集中式狀態(tài)管理架構(gòu)。它借鑒了 Flux 和 Redux 的設(shè)計(jì)思想,但簡(jiǎn)化了概念,并且采用了一種為能更好發(fā)揮 Vue.js 數(shù)據(jù)響應(yīng)機(jī)制而專門設(shè)計(jì)的實(shí)現(xiàn)。
2、Vuex 的四個(gè)核心概念分別是:
The state tree:Vuex 使用單一狀態(tài)樹,用一個(gè)對(duì)象就包含了全部的應(yīng)用層級(jí)狀態(tài)。至此它便作為一個(gè)『唯一數(shù)據(jù)源(SSOT)』而存在。這也意味著,每個(gè)應(yīng)用將僅僅包含一個(gè) store 實(shí)例。單狀態(tài)樹讓我們能夠直接地定位任一特定的狀態(tài)片段,在調(diào)試的過程中也能輕易地取得整個(gè)當(dāng)前應(yīng)用狀態(tài)的快照。
Getters: 用來從 store 獲取 Vue 組件數(shù)據(jù)。
Mutators: 事件處理器用來驅(qū)動(dòng)狀態(tài)的變化。
Actions: 可以給組件使用的函數(shù),以此用來驅(qū)動(dòng)事件處理器 mutations
3、Vuex 應(yīng)用中數(shù)據(jù)的流向(Vuex 官方圖)
- 數(shù)據(jù)流都是單向的
- 組件能夠調(diào)用 action
- action 用來派發(fā) Mutation
- 只有 mutation 可以改變狀態(tài)
- store 是響應(yīng)式的,無論 state 什么時(shí)候更新,組件都將同步更新
參考文獻(xiàn):
思否-飛躍
思否-離塵不理人
總結(jié)
以上是生活随笔為你收集整理的Vue使用Vuex一步步封装并使用store的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue项目将token存在(vuex)s
- 下一篇: Vuex使用总结