目錄
- 1.什么是vuex?
- 2.為什么要使用Vuex?
- 3.vuex的核心概念?||如何在組件中去使用vuex的值和方法?||在vuex中使用異步修改?
- 4.vuex 輔助函數
- 5.action異步操作
- 6.vuex在vue-cli中的應用
- 1.什么是vuex?
Vuex 是一個專為 Vue.js 應用程序開發的狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,并以相應的規則保證狀態以一種可預測的方式發生變化。
上圖中綠色虛線包裹起來的部分就是Vuex的核心, state中保存的就是公共狀態, 改變state的唯一方式就是通過mutations進行更改. 可能你現在看這張圖有點不明白, 等經過本文的解釋和案例演示, 再回來看這張圖, 相信你會有更好的理解.
2. 為什么要使用Vuex?
試想這樣的場景, 比如一個Vue的根實例下面有一個根組件名為App.vue
, 它下面有兩個子組件A.vue
和B.vue
, App.vue
想要與A.vue
或者B.vue
通訊可以通過props傳值的方式, 但是如果A.vue
和B.vue
之間的通訊就很麻煩了, 他們需要共有的父組件通過自定義事件進行實現, A組件想要和B組件通訊往往是這樣的:
- A組件說: "報告老大, 能否幫我托個信給小弟B" => dispatch一個事件給App
- App老大說: "包在我身上, 它需要監聽A組件的dispatch的時間, 同時需要broadcast一個事件給B組件"
- B小弟說: "信息已收到", 它需要on監聽App組件分發的事件
這只是一條通訊路徑, 如果父組件下有多個子組件, 子組件之間通訊的路徑就會變的很繁瑣, 父組件需要監聽大量的事件, 還需要負責分發給不同的子組件, 很顯然這并不是我們想要的組件化的開發體驗.
Vuex就是為了解決這一問題出現的
3. Vuex的核心概念?
在介紹Vuex的核心概念之前, 我使用vue-cli
初始化了一個demo, 準備以代碼的形式來說明Vuex的核心概念.這個demo分別有兩個組件ProductListOne.vue
和ProductListTwo.vue
, 在App.vue
的datat
中保存著共有的商品列表, 代碼和初始化的效果如下圖所示:
引入Vuex
下載vuex
: npm install vuex --save
在main.js
添加:
import Vuex from 'vuex'
Vue.use( Vuex );
const store = new Vuex.Store({
//待添加
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
//App.vue中的初始化代碼
<template>
<div id="app">
<product-list-one v-bind:products="products"></product-list-one>
<product-list-two v-bind:products="products"></product-list-two>
</div>
</template>
<script>
import ProductListOne from './components/ProductListOne.vue'
import ProductListTwo from './components/ProductListTwo.vue'
export default {
name: 'app',
components: {
'product-list-one': ProductListOne,
'product-list-two': ProductListTwo
},
data () {
return {
products: [
{name: '鼠標', price: 20},
{name: '鍵盤', price: 40},
{name: '耳機', price: 60},
{name: '顯示屏', price: 80}
]
}
}
}
</script>
<style>
body{
font-family: Ubuntu;
color: #555;
}
</style>
//ProductListOne.vue
<template>
<div id="product-list-one">
<h2>Product List One</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['products'],
data () {
return {
}
}
}
</script>
<style scoped>
#product-list-one{
background: #FFF8B1;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-one ul{
padding: 0;
}
#product-list-one li{
display: inline-block;
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #E8800C;
}
</style>
//ProductListTwo.vue
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['products'],
data () {
return {
}
}
}
</script>
<style scoped>
#product-list-two{
background: #D1E4FF;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-two ul{
padding: 0;
list-style-type: none;
}
#product-list-two li{
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #860CE8;
display: block;
}
</style>
核心概念1: State
state
就是Vuex中的公共的狀態, 我是將state
看作是所有組件的data
, 用于保存所有組件的公共數據.
- 此時我們就可以把
App.vue
中的兩個組件共同使用的data抽離出來, 放到state
中,代碼如下:
//main.js
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
Vue.use( Vuex )
const store = new Vuex.Store({
state:{
products: [
{name: '鼠標', price: 20},
{name: '鍵盤', price: 40},
{name: '耳機', price: 60},
{name: '顯示屏', price: 80}
]
}
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
- 此時,
ProductListOne.vue
和ProductListTwo.vue
也需要做相應的更改
//ProductListOne.vue
export default {
data () {
return {
products : this.$store.state.products //獲取store中state的數據
}
}
}
//ProductListTwo.vue
export default {
data () {
return {
products: this.$store.state.products //獲取store中state的數據
}
}
}
-
此時的頁面如下圖所示, 可以看到, 將公共數據抽離出來后, 頁面沒有發生變化.
state效果
核心概念2: Getters
我將getters
屬性理解為所有組件的computed
屬性, 也就是計算屬性. vuex的官方文檔也是說到可以將getter理解為store的計算屬性, getters的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變才會被重新計算。
- 此時,我們可以在
main.js
中添加一個getters
屬性, 其中的saleProducts
對象將state
中的價格減少一半(除以2)
//main.js
const store = new Vuex.Store({
state:{
products: [
{name: '鼠標', price: 20},
{name: '鍵盤', price: 40},
{name: '耳機', price: 60},
{name: '顯示屏', price: 80}
]
},
getters:{ //添加getters
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
}
})
- 將
productListOne.vue
中的products
的值更換為this.$store.getters.saleProducts
export default {
data () {
return {
products : this.$store.getters.saleProducts
}
}
}
- 現在的頁面中,Product List One中的每項商品的價格都減少了一半
核心概念3: Mutations
我將mutaions
理解為store
中的methods
, mutations
對象中保存著更改數據的回調函數,該函數名官方規定叫type
, 第一個參數是state
, 第二參數是payload
, 也就是自定義的參數.
- 下面,我們在
main.js
中添加mutations
屬性,其中minusPrice
這個回調函數用于將商品的價格減少payload
這么多, 代碼如下:
//main.js
const store = new Vuex.Store({
state:{
products: [
{name: '鼠標', price: 20},
{name: '鍵盤', price: 40},
{name: '耳機', price: 60},
{name: '顯示屏', price: 80}
]
},
getters:{
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
},
mutations:{ //添加mutations
minusPrice (state, payload ) {
let newPrice = state.products.forEach( product => {
product.price -= payload
})
}
}
})
- 在
ProductListTwo.vue
中添加一個按鈕,為其添加一個點擊事件, 給點擊事件觸發minusPrice
方法
//ProductListTwo.vue
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
<button @click="minusPrice">減少價格</button> //添加按鈕
</ul>
</div>
</template>
- 在
ProductListTwo.vue
中注冊minusPrice
方法, 在該方法中commitmutations
中的minusPrice
這個回調函數
注意:調用mutaions中回調函數, 只能使用store.commit(type, payload)
//ProductListTwo.vue
export default {
data () {
return {
products: this.$store.state.products
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2); //提交`minusPrice,payload為2
}
}
}
-
添加按鈕, 可以發現, Product List Two中的價格減少了2, 當然你可以自定義
payload
,以此自定義減少對應的價格.mutations效果(Product List One中的價格沒有發生變化, 是因為
getters
將價格進行了緩存)
核心概念4: Actions
actions
類似于 mutations
,不同在于:
actions
提交的是mutations
而不是直接變更狀態actions
中可以包含異步操作,mutations
中絕對不允許出現異步actions
中的回調函數的第一個參數是context
, 是一個與store
實例具有相同屬性和方法的對象此時,我們在
store
中添加actions
屬性, 其中minusPriceAsync
采用setTimeout
來模擬異步操作,延遲2s執行 該方法用于異步改變我們剛才在mutaions
中定義的minusPrice
//main.js
const store = new Vuex.Store({
state:{
products: [
{name: '鼠標', price: 20},
{name: '鍵盤', price: 40},
{name: '耳機', price: 60},
{name: '顯示屏', price: 80}
]
},
getters:{
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
},
mutations:{
minusPrice (state, payload ) {
let newPrice = state.products.forEach( product => {
product.price -= payload
})
}
},
actions:{ //添加actions
minusPriceAsync( context, payload ) {
setTimeout( () => {
context.commit( 'minusPrice', payload ); //context提交
}, 2000)
}
}
})
- 在
ProductListTwo.vue
中添加一個按鈕,為其添加一個點擊事件, 給點擊事件觸發minusPriceAsync
方法
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
<button @click="minusPrice">減少價格</button>
<button @click="minusPriceAsync">異步減少價格</button> //添加按鈕
</ul>
</div>
</template>
- 在
ProductListTwo.vue
中注冊minusPriceAsync
方法, 在該方法中dispatchactions
中的minusPriceAsync
這個回調函數
export default {
data () {
return {
products: this.$store.state.products
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2);
},
minusPriceAsync() {
this.$store.dispatch('minusPriceAsync', 5); //分發actions中的minusPriceAsync這個異步函數
}
}
}
-
添加按鈕, 可以發現, Product List Two中的價格延遲2s后減少了5
actions效果
核心概念5: Modules
由于使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常復雜時,store 對象就有可能變得相當臃腫。為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態
- 4.vuex 輔助函數
#mapState
輔助函數
當一個組件需要獲取多個狀態時候,將這些狀態都聲明為計算屬性會有些重復和冗余。為了解決這個問題,我們可以使用 mapState
輔助函數幫助我們生成計算屬性,讓你少按幾次鍵:
用法:
- 對象
// 在單獨構建的版本中輔助函數為 Vuex.mapState
import { mapState } from 'vuex' // 引入
export default {
// ...
computed: mapState({
// 箭頭函數
count: state => state.count,
// 傳字符串參數 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態localCount,必須使用常規函數
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
如果使用箭頭函數,當vuex的state和當前組件的state,含有相同的變量名稱時,this獲取的是vuex中的變量,而不是局部變量
-
數組
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState 傳一個字符串數組。
computed: mapState([
// 映射 this.count 為 store.state.count
'count'
])
-
對象展開運算符
mapState函數返回的是一個對象。如果需要將它與局部計算屬性混合使用,通常我們需要一個工具函數將多個對象合并為一個,以使我們可以將最終對象傳給computed屬性。
computed: {
localComputed () {},
...mapState({
//...
})
}
也可以使用`...mapState([])`,
但前提是映射的計算屬性的名稱與state的子節點名稱相同,如果state在vuex的modules中,則不成功。
#mapGetters
輔助函數
mapGetters
輔助函數僅僅是將 store 中的 getter 映射到局部計算屬性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用對象展開運算符將 getter 混入 computed 對象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想將一個 getter 屬性另取一個名字,使用對象形式:
mapGetters({
// 把 `this.doneCount` 映射為 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
#mapMutations
輔助函數
在組件中提交 Mutation
你可以在組件中使用 this.$store.commit('xxx')
提交 mutation,或者使用 mapMutations
輔助函數將組件中的 methods 映射為 store.commit
調用(需要在根節點注入 store
)。
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 將 `this.increment()` 映射為 `this.$store.commit('increment')`
// `mapMutations` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 將 `this.add()` 映射為 `this.$store.commit('increment')`
})
}
}
下一步:Action
在 mutation 中混合異步調用會導致你的程序很難調試。例如,當你調用了兩個包含異步回調的 mutation 來改變狀態,你怎么知道什么時候回調和哪個先回調呢?這就是為什么我們要區分這兩個概念。在 Vuex 中,mutation 都是同步事務:
store.commit('increment')
// 任何由 "increment" 導致的狀態變更都應該在此刻完成。
為了處理異步操作,讓我們來看一看 Action。
#mapActions輔助函數
在組件中分發 Action
你在組件中使用 this.$store.dispatch('xxx')
分發 action,或者使用 mapActions
輔助函數將組件的 methods 映射為 store.dispatch
調用(需要先在根節點注入 store
):
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 將 `this.increment()` 映射為 `this.$store.dispatch('increment')`
// `mapActions` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 將 `this.add()` 映射為 `this.$store.dispatch('increment')`
})
}
}
- 5.action異步操作
Action 提交的是 mutation,而不是直接變更狀態。
Action 可以包含任意異步操作。
先注冊一個action
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用context.commit
提交一個 mutation,或者通過 context.state
和context.getters
來獲取 state 和 getters。
用參數結構簡化代碼
actions: {
increment ({ commit }) {
commit('increment')
}
}
分發action
store.dispatch('increment')
mutation 必須同步 ! 執行 Action 就不受約束!我們可以在 action 內部執行異步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions 支持同樣的載荷方式和對象方式進行分發:
// 以載荷形式分發
store.dispatch('incrementAsync', {
amount: 10
})
// 以對象形式分發
store.dispatch({
type: 'incrementAsync',
amount: 10
})
例子 調用異步 API 和分發多重 mutation:
actions: {
checkout ({ commit, state }, products) {
// 把當前購物車的物品備份起來
const savedCartItems = [...state.cart.added]
// 發出結賬請求,然后樂觀地清空購物車
commit(types.CHECKOUT_REQUEST)
// 購物 API 接受一個成功回調和一個失敗回調
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失敗操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
組合 Action
Action 通常是異步的,那么如何知道 action 什么時候結束呢?更重要的是,我們如何才能組合多個 action,以處理更加復雜的異步流程?
首先,你需要明白 store.dispatch 可以處理被觸發的 action 的處理函數返回的 Promise,并且 store.dispatch 仍舊返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
現在你可以:
store.dispatch('actionA').then(() => {
// ...
})
在另外一個 action 中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
最后,如果我們利用 async / await,我們可以如下組合 action:
// 假設 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
一個 store.dispatch 在不同模塊中可以觸發多個 action 函數。在這種情況下,只有當所有觸發函數完成后,返回的 Promise 才會執行。
- 6.vuex在vue-cli中的應用
精簡版介紹vuex
const store = new Vuex.Store({
state: {
name: 'weish',
age: 22
},
getters: {
personInfo(state) {
return `My name is ${state.name}, I am ${state.age}`;
}
}
mutations: {
SET_AGE(state, age) {
commit(age, age);
}
},
actions: {
nameAsyn({commit}) {
setTimeout(() => {
commit('SET_AGE', 18);
}, 1000);
}
},
modules: {
a: modulesA
}
}
這個就是最基本也是完整的vuex代碼:
vuex 包含有五個基本的對象:
1、state:存儲狀態,也就是全局變量;
2、getters:派生狀態。也就是set、get中的get,有兩個可選參數:state、getters,分別可以獲取state中的變量和其他的getters。外部調用方式:store.getters.personInfo(),就和vue的computed差不多;
3、mutations:提交狀態修改。也就是set、get中的set,這是vuex中唯一修改state的方式,但不支持異步操作。第一個參數默認是state,外部調用方式:store.commit('SET_AGE', 18),和vue中的methods類似。
4、actions:和mutations類似,不過actions支持異步操作。第一個參數默認是和store具有相同參數屬性的對象。外部調用方式:store.dispatch('nameAsyn')。
5、modules:store的子模塊,內容就相當于是store的一個實例。調用方式和前面介紹的相似,只是要加上當前子模塊名,如:store.a.getters.xxx()。
vuex在vue-cli目錄結構
├── index.html
├── main.js
├── components
└── store
├── index.js # 我們組裝模塊并導出 store 的地方
├── state.js # 根級別的 state
├── getters.js # 根級別的 getter
├── mutation-types.js # 根級別的mutations名稱(官方推薦mutions方法名使用大寫)
├── mutations.js # 根級別的 mutation
├── actions.js # 根級別的 action
└── modules
├── m1.js # 模塊1
└── m2.js # 模塊2
state.js示例:
const state = {
name: 'weish',
age: 22
};
export default state;
getters.js示例(我們一般使用getters來獲取state的狀態,而不是直接使用state):
export const name = (state) => {
return state.name;
}
export const age = (state) => {
return state.age
}
export const other = (state) => {
return `My name is ${state.name}, I am ${state.age}.`;
}
mutation-type.js示例(我們會將所有mutations的函數名放在這個文件里):
export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';
mutations.js示例:
import * as types from './mutation-type.js';
export default {
[types.SET_NAME](state, name) {
state.name = name;
},
[types.SET_AGE](state, age) {
state.age = age;
}
};
actions.js示例(異步操作、多個commit時):
import * as types from './mutation-type.js';
export default {
nameAsyn({commit}, {age, name}) {
commit(types.SET_NAME, name);
commit(types.SET_AGE, age);
}
};
modules--m1.js示例(如果不是很復雜的應用,一般來講是不會分模塊的):
export default {
state: {},
getters: {},
mutations: {},
actions: {}
};
index.js示例(組裝vuex):
import vue from 'vue';
import vuex from 'vuex';
import state from './state.js';
import * as getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';
import m1 from './modules/m1.js';
import m2 from './modules/m2.js';
import createLogger from 'vuex/dist/logger'; // 修改日志
vue.use(vuex);
const debug = process.env.NODE_ENV !== 'production'; // 開發環境中為true,否則為false
export default new vuex.Store({
state,
getters,
mutations,
actions,
modules: {
m1,
m2
},
plugins: debug ? [createLogger()] : [] // 開發環境下顯示vuex的狀態修改
});
最后將store實例掛載到main.js里面的vue上去就行了
import store from './store/index.js';
new Vue({
el: '#app',
store,
render: h => h(App)
});
在vue組件中使用時,我們通常會使用mapGetters、mapActions、mapMutations,然后就可以按照vue調用methods和computed的方式去調用這些變量或函數,示例如下:
import {mapGetters, mapMutations, mapActions} from 'vuex';
/* 只寫組件中的script部分 */
export default {
computed: {
...mapGetters([
name,
age
])
},
methods: {
...mapMutations({
setName: 'SET_NAME',
setAge: 'SET_AGE'
}),
...mapActions([
nameAsyn
])
}
};