Vuex
1. 什么是狀態(tài)管理
狀態(tài)管理
- 狀態(tài)管理模式
- 集中式存儲(chǔ)管理
- Vuex 狀態(tài)管理
2. Vuex 的基本使用
- 終端插件安裝
npm install vuex --save
- mutations -> devtools
Vuex 管理插件(Devtools)
// 瀏覽器中安裝:菜單-->擴(kuò)展程序-->網(wǎng)上搜索 devtools-->下載
- 基本結(jié)構(gòu)
import Vue from "vue"
import Vuex from "vuex"
// 1. 安裝插件
Vue.use(Vuex)
// 2. 創(chuàng)建對(duì)象
const state = {}
const store = new Vuex.Store({
// 傳入各種參數(shù)
state,
mutations,
actions,
getters,
modules: {
// 針對(duì)每個(gè)模塊進(jìn)行使用
a: moduleA,
b: moduleB,
},
})
// 3. 導(dǎo)出
export default store
3. 核心概念
-
state
用來(lái)存儲(chǔ)各種共享變量及數(shù)據(jù)(單一狀態(tài)樹)
-
缺點(diǎn):
- 效率低卵贱,不方便
- 優(yōu)點(diǎn):
- 提高安全性
- 更容易維護(hù)
// 2. 創(chuàng)建對(duì)象
const state = {
// 定義共享變量(單一狀態(tài)樹)
counter: 15,
students: [
{ id: 110, name: "Tom", age: 18 },
{ id: 111, name: "Bob", age: 35 },
{ id: 112, name: "Jerry", age: 24 },
{ id: 113, name: "Sam", age: 9 },
],
info: {
name: "Tom",
age: 18,
height: 1.88,
},
}
const store = new Vuex.Store({
state,
})
- getters
用來(lái)寫入各種相關(guān)的計(jì)算屬性(類似于 computed)
/* getters.js 文件 */
export default {
// 計(jì)算屬性
powerCounter(state) {
return state.counter * state.counter
},
moreAgeStu(state) {
return age => {
return state.students.filter(s => s.age > age)
}
},
more20stu(state) {
return state.students.filter(s => s.age >= 20)
},
more20stuLength(state, getters) {
return getters.more20stu.length
},
}
- mutation
用來(lái)寫入各種相關(guān)的使用方法(類似于 methods)
- 字符串的
事件類型(type)
- 一個(gè)
回調(diào)函數(shù)(handler)
仙蚜,該回調(diào)函數(shù)的第一個(gè)參數(shù)就是 state - 傳遞參數(shù)
/* mutations.js 文件 */
// 對(duì)方法進(jìn)行處理更新,方便使用(類型常量)
export const INCREMENT = "increment"
export default {
// 狀態(tài)更新(定義方法)
[INCREMENT](state) {
state.counter++
},
decrement(state) {
state.counter--
},
incrementCount(state, count) {
state.counter += count
},
updateInfo(state) {
state.info.name = "coder" // 修改姓名
Vue.set(state.info, "address", "LoSan") // 添加元素(響應(yīng)式)
Vue.delete(state.info, "age") // 刪除元素(響應(yīng)式)
},
}
- actions
用來(lái)處理異步操作
/* actions.js 文件 */
export default {
// 異步操作 (context):上下文==>等同于store
aUpdateInfo(context) {
setTimeout(() => {
context.commit("updateInfo")
}, 1000)
},
}
- modules(模塊分裝)
將模塊分開分裝胖眷,可以容易閱讀
const moduleA = {
// A 模塊內(nèi)容
}
const moduleB = {
// B 模塊內(nèi)容
}
const store = new Vuex.Store({
modules: {
// 針對(duì)每個(gè)模塊進(jìn)行使用
a: moduleA,
b: moduleB,
},
})
注意 1: 提交風(fēng)格(commit)
- 普通風(fēng)格
this.$store.commit("increment")
- type 風(fēng)格
// 提交之后 類似于一個(gè) payload對(duì)象
this.$store.commit({
type: "incrementCount",
count,
})
> 注意2: 響應(yīng)式
> 原理:這些屬性都會(huì)被加入到響應(yīng)式系統(tǒng)中建瘫,而響應(yīng)式系統(tǒng)會(huì)監(jiān)聽屬性的變化钾虐,當(dāng)屬性發(fā)生變化時(shí)眼五,會(huì)通知所有界面中用到該屬性的地方咳胃,讓界面發(fā)生刷新
#### 4. 目錄組織方式
> modules 文件存放每個(gè)模塊
> actions.js 放入異步操作代碼
> getters.js 放入相關(guān)計(jì)算屬性代碼
> mutations.js 放入相關(guān)方法代碼
> index.js 放入最基本的 vuex 使用和共享變量 state
![meun.png](https://upload-images.jianshu.io/upload_images/25634883-7240a7b6a01198b9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)