一、初識VueX
1.1 關于VueX
VueX是適用于在Vue項目開發(fā)時使用的狀態(tài)管理工具。試想一下,如果在一個項目開發(fā)中頻繁的使用組件傳參的方式來同步data中的值,一旦項目變得很龐大,管理和維護這些值將是相當棘手的工作。為此,Vue為這些被多個組件頻繁使用的值提供了一個統(tǒng)一管理的工具——VueX。在具有VueX的Vue項目中,我們只需要把這些值定義在VueX中,即可在整個Vue項目的組件中使用。
1.2 安裝
由于VueX是在學習VueCli后進行的,所以在下文出現(xiàn)的項目的目錄請參照VueCli 2.x構(gòu)建的目錄。
以下步驟的前提是你已經(jīng)完成了Vue項目構(gòu)建,并且已轉(zhuǎn)至該項目的文件目錄下。
-
Npm安裝Vuex
npm i vuex -s -
在項目的根目錄下新增一個
store文件夾,在該文件夾內(nèi)創(chuàng)建index.js此時你的項目的
src文件夾應當是這樣的│ App.vue │ main.js │ ├─assets │ logo.png │ ├─components │ HelloWorld.vue │ ├─router │ index.js │ └─store index.js
1.3 使用
1.3.1 初始化store下index.js中的內(nèi)容
import Vue from 'vue'
import Vuex from 'vuex'
//掛載Vuex
Vue.use(Vuex)
//創(chuàng)建VueX對象
const store = new Vuex.Store({
state:{
//存放的鍵值對就是所要管理的狀態(tài)
name:'helloVueX'
}
})
export default store
1.3.2 將store掛載到當前項目的Vue實例當中去
打開main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //store:store 和router一樣,將我們創(chuàng)建的Vuex實例掛載到這個vue實例中
render: h => h(App)
})
1.3.3 在組件中使用Vuex
例如在App.vue中,我們要將state中定義的name拿來在h1標簽中顯示
<template>
<div id='app'>
name:
<h1>{{ $store.state.name }}</h1>
</div>
</template>
或者要在組件方法中使用
...,
methods:{
add(){
console.log(this.$store.state.name)
}
},
...
注意,請不要在此處更改state中的狀態(tài)的值,后文中將會說明
1.4 安裝Vue開發(fā)工具VueDevtools
在Vue項目開發(fā)中,需要監(jiān)控項目中得各種值,為了提高效率,Vue提供了一款瀏覽器擴展——VueDevtools。

在學習VueX時,更為需要使用該插件。關于該插件的使用可以移步官網(wǎng),在此不再贅敘。
二、VueX中的核心內(nèi)容
在VueX對象中,其實不止有state,還有用來操作state中數(shù)據(jù)的方法集,以及當我們需要對state中的數(shù)據(jù)需要加工的方法集等等成員。
成員列表:
- state 存放狀態(tài)
- mutations state成員操作
- getters 加工state成員給外界
- actions 異步操作
- modules 模塊化狀態(tài)管理
2.1 VueX的工作流程

首先,Vue組件如果調(diào)用某個VueX的方法過程中需要向后端請求時或者說出現(xiàn)異步操作時,需要dispatch VueX中actions的方法,以保證數(shù)據(jù)的同步??梢哉f,action的存在就是為了讓mutations中的方法能在異步操作中起作用。
如果沒有異步操作,那么我們就可以直接在組件內(nèi)提交狀態(tài)中的Mutations中自己編寫的方法來達成對state成員的操作。注意,1.3.3節(jié)中有提到,不建議在組件中直接對state中的成員進行操作,這是因為直接修改(例如:this.$store.state.name = 'hello')的話不能被VueDevtools所監(jiān)控到。
最后被修改后的state成員會被渲染到組件的原位置當中去。
2.2 Mutations
mutations是操作state數(shù)據(jù)的方法的集合,比如對該數(shù)據(jù)的修改、增加、刪除等等。
2.2.1 Mutations使用方法
mutations方法都有默認的形參:
([state] [,payload])
-
state是當前VueX對象中的state -
payload是該方法在被調(diào)用時傳遞參數(shù)使用的
例如,我們編寫一個方法,當被執(zhí)行時,能把下例中的name值修改為"jack",我們只需要這樣做
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.store({
state:{
name:'helloVueX'
},
mutations:{
//es6語法,等同edit:funcion(){...}
edit(state){
state.name = 'jack'
}
}
})
export default store
而在組件中,我們需要這樣去調(diào)用這個mutation——例如在App.vue的某個method中:
this.$store.commit('edit')
2.2.2 Mutation傳值
在實際生產(chǎn)過程中,會遇到需要在提交某個mutation時需要攜帶一些參數(shù)給方法使用。
單個值提交時:
this.$store.commit('edit',15)
當需要多參提交時,推薦把他們放在一個對象中來提交:
this.$store.commit('edit',{age:15,sex:'男'})
接收掛載的參數(shù):
edit(state,payload){
state.name = 'jack'
console.log(payload) // 15或{age:15,sex:'男'}
}
另一種提交方式
this.$store.commit({
type:'edit',
payload:{
age:15,
sex:'男'
}
})
2.2.3 增刪state中的成員
為了配合Vue的響應式數(shù)據(jù),我們在Mutations的方法中,應當使用Vue提供的方法來進行操作。如果使用delete或者xx.xx = xx的形式去刪或增,則Vue不能對數(shù)據(jù)進行實時響應。
-
Vue.set 為某個對象設置成員的值,若不存在則新增
例如對state對象中添加一個age成員
Vue.set(state,"age",15) -
Vue.delete 刪除成員
將剛剛添加的age成員刪除
Vue.delete(state,'age')
2.3 Getters
可以對state中的成員加工后傳遞給外界
Getters中的方法有兩個默認參數(shù)
- state 當前VueX對象中的狀態(tài)對象
- getters 當前getters對象,用于將getters下的其他getter拿來用
例如
getters:{
nameInfo(state){
return "姓名:"+state.name
},
fullInfo(state,getters){
return getters.nameInfo+'年齡:'+state.age
}
}
組件中調(diào)用
this.$store.getters.fullInfo
2.4 Actions
由于直接在mutation方法中進行異步操作,將會引起數(shù)據(jù)失效。所以提供了Actions來專門進行異步操作,最終提交mutation方法。
Actions中的方法有兩個默認參數(shù)
-
context上下文(相當于箭頭函數(shù)中的this)對象 -
payload掛載參數(shù)
例如,我們在兩秒中后執(zhí)行2.2.2節(jié)中的edit方法
由于setTimeout是異步操作,所以需要使用actions
actions:{
aEdit(context,payload){
setTimeout(()=>{
context.commit('edit',payload)
},2000)
}
}
在組件中調(diào)用:
this.$store.dispatch('aEdit',{age:15})
改進:
由于是異步操作,所以我們可以為我們的異步操作封裝為一個Promise對象
aEdit(context,payload){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
context.commit('edit',payload)
resolve()
},2000)
})
}
2.5 Models
當項目龐大,狀態(tài)非常多時,可以采用模塊化管理模式。Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割。
models:{
a:{
state:{},
getters:{},
....
}
}
組件內(nèi)調(diào)用模塊a的狀態(tài):
this.$store.state.a
而提交或者dispatch某個方法和以前一樣,會自動執(zhí)行所有模塊內(nèi)的對應type的方法:
this.$store.commit('editKey')
this.$store.dispatch('aEditKey')
2.5.1 模塊的細節(jié)
-
模塊中
mutations和getters中的方法接受的第一個參數(shù)是自身局部模塊內(nèi)部的statemodels:{ a:{ state:{key:5}, mutations:{ editKey(state){ state.key = 9 } }, .... } } -
getters中方法的第三個參數(shù)是根節(jié)點狀態(tài)models:{ a:{ state:{key:5}, getters:{ getKeyCount(state,getter,rootState){ return rootState.a.key + state.key } }, .... } } -
actions中方法獲取局部模塊狀態(tài)是context.state,根節(jié)點狀態(tài)是context.rootStatemodels:{ a:{ state:{key:5}, actions:{ aEidtKey(context){ if(context.state.key === context.rootState.a.key){ context.commit('editKey') } } }, .... } }
三、規(guī)范目錄結(jié)構(gòu)
如果把整個store都放在index.js中是不合理的,所以需要拆分。比較合適的目錄格式如下:
store:.
│ actions.js
│ getters.js
│ index.js
│ mutations.js
│ mutations_type.js ##該項為存放mutaions方法常量的文件,按需要可加入
│
└─modules
Astore.js
對應的內(nèi)容存放在對應的文件中,和以前一樣,在index.js中存放并導出store。state中的數(shù)據(jù)盡量放在index.js中。而modules中的Astore局部模塊狀態(tài)如果多的話也可以進行細分。
作者:怪獸難吃素
原文鏈接:http://www.itdecent.cn/p/2e5973fe1223