一、初識VueX
1.1 關於VueX
VueX
是適用於在Vue
項目開發時使用的狀態管理工具。試想一下,如果在一個項目開發中頻繁的使用組件傳參的方式來同步data
中的值,一旦項目變得很龐大,管理和維護這些值將是相當棘手的工作。爲此,Vue
爲這些被多個組件頻繁使用的值提供了一個統一管理的工具——VueX
。在具有VueX
的Vue項目中,我們只需要把這些值定義在VueX中,即可在整個Vue項目的組件中使用。
1.2 安裝
由於VueX
是在學習VueCli
後進行的,所以在下文出現的項目的目錄請參照VueCli 2.x
構建的目錄。
以下步驟的前提是你已經完成了Vue項目構建,並且已轉至該項目的文件目錄下。
Npm安裝Vuex
npm i vuex -s
在項目的根目錄下新增一個store
文件夾,在該文件夾內創建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
中的內容
import Vue from 'vue'
import Vuex from 'vuex'
//掛載Vuex
Vue.use(Vuex)
//創建VueX對象
const store = new Vuex.Store({
state:{
//存放的鍵值對就是所要管理的狀態
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一樣,將我們創建的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
中的狀態的值,後文中將會說明
1.4 安裝Vue開發工具VueDevtools
在Vue項目開發中,需要監控項目中得各種值,爲了提高效率,Vue提供了一款瀏覽器擴展——VueDevtools。
在學習VueX時,更爲需要使用該插件。關於該插件的使用可以移步官網,在此不再贅敘。
二、VueX中的核心內容
在VueX對象中,其實不止有state
,還有用來操作state
中數據的方法集,以及當我們需要對state
中的數據需要加工的方法集等等成員。
成員列表:
- state 存放狀態
- mutations state成員操作
- getters 加工state成員給外界
- actions 異步操作
- modules 模塊化狀態管理
2.1 VueX的工作流程
首先,Vue
組件如果調用某個VueX
的方法過程中需要向後端請求時或者說出現異步操作時,需要dispatch
VueX中actions
的方法,以保證數據的同步。可以說,action
的存在就是爲了讓mutations
中的方法能在異步操作中起作用。
如果沒有異步操作,那麼我們就可以直接在組件內提交狀態中的Mutations
中自己編寫的方法來達成對state
成員的操作。注意,1.3.3節
中有提到,不建議在組件中直接對state
中的成員進行操作,這是因爲直接修改(例如:this.$store.state.name = 'hello'
)的話不能被VueDevtools
所監控到。
最後被修改後的state成員會被渲染到組件的原位置當中去。
2.2 Mutations
mutations
是操作state
數據的方法的集合,比如對該數據的修改、增加、刪除等等。
2.2.1 Mutations使用方法
mutations
方法都有默認的形參:
([state] [,payload])
state
是當前VueX
對象中的state
payload
是該方法在被調用時傳遞參數使用的
例如,我們編寫一個方法,當被執行時,能把下例中的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
而在組件中,我們需要這樣去調用這個mutation
——例如在App.vue的某個method
中:
this.$store.commit('edit')
2.2.2 Mutation傳值
在實際生產過程中,會遇到需要在提交某個mutation
時需要攜帶一些參數給方法使用。
單個值提交時:
this.$store.commit('edit',15)
當需要多參提交時,推薦把他們放在一個對象中來提交:
this.$store.commit('edit',{age:15,sex:'男'})
接收掛載的參數:
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的響應式數據,我們在Mutations的方法中,應當使用Vue提供的方法來進行操作。如果使用delete
或者xx.xx = xx
的形式去刪或增,則Vue不能對數據進行實時響應。
Vue.set 爲某個對象設置成員的值,若不存在則新增
例如對state對象中添加一個age成員
Vue.set(state,"age",15)
Vue.delete 刪除成員
將剛剛添加的age成員刪除
Vue.delete(state,'age')
2.3 Getters
可以對state中的成員加工後傳遞給外界
Getters中的方法有兩個默認參數
- state 當前VueX對象中的狀態對象
- getters 當前getters對象,用於將getters下的其他getter拿來用
例如
getters:{
nameInfo(state){
return "姓名:"+state.name
},
fullInfo(state,getters){
return getters.nameInfo+'年齡:'+state.age
}
}
組件中調用
this.$store.getters.fullInfo
2.4 Actions
由於直接在mutation
方法中進行異步操作,將會引起數據失效。所以提供了Actions來專門進行異步操作,最終提交mutation
方法。
Actions
中的方法有兩個默認參數
context
上下文(相當於箭頭函數中的this)對象payload
掛載參數
例如,我們在兩秒中後執行2.2.2
節中的edit
方法
由於setTimeout
是異步操作,所以需要使用actions
actions:{
aEdit(context,payload){
setTimeout(()=>{
context.commit('edit',payload)
},2000)
}
}
在組件中調用:
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
當項目龐大,狀態非常多時,可以採用模塊化管理模式。Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter
、甚至是嵌套子模塊——從上至下進行同樣方式的分割。
models:{
a:{
state:{},
getters:{},
....
}
}
組件內調用模塊a的狀態:
this.$store.state.a
而提交或者dispatch
某個方法和以前一樣,會自動執行所有模塊內的對應type
的方法:
this.$store.commit('editKey')
this.$store.dispatch('aEditKey')
2.5.1 模塊的細節
模塊中mutations
和getters
中的方法接受的第一個參數是自身局部模塊內部的state
models:{
a:{
state:{key:5},
mutations:{
editKey(state){
state.key = 9
}
},
....
}
}
getters
中方法的第三個參數是根節點狀態
models:{
a:{
state:{key:5},
getters:{
getKeyCount(state,getter,rootState){
return rootState.key + state.key
}
},
....
}
}
actions
中方法獲取局部模塊狀態是context.state
,根節點狀態是context.rootState
models:{
a:{
state:{key:5},
actions:{
aEidtKey(context){
if(context.state.key === context.rootState.key){
context.commit('editKey')
}
}
},
....
}
}
三、規範目錄結構
如果把整個store
都放在index.js
中是不合理的,所以需要拆分。比較合適的目錄格式如下:
store:.
│ actions.js
│ getters.js
│ index.js
│ mutations.js
│ mutations_type.js ##該項爲存放mutaions方法常量的文件,按需要可加入
│
└─modules
Astore.js
對應的內容存放在對應的文件中,和以前一樣,在index.js
中存放並導出store
。state
中的數據儘量放在index.js
中。而modules
中的Astore
局部模塊狀態如果多的話也可以進行細分。