一. 什么是Vuex?

Vuex是一個專門為Vue.js應用程序開發(fā)的狀態(tài)管理模式, 它采用集中式存儲管理所有組件的公共狀態(tài), 并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化.

上圖中綠色虛線包裹起來的部分就是Vuex的核心, state中保存的就是公共狀態(tài), 改變state的唯一方式就是通過mutations進行更改. 可能你現(xiàn)在看這張圖有點不明白, 等經過本文的解釋和案例演示, 再回來看這張圖, 相信你會有更好的理解.
二. 為什么要使用Vuex?
試想這樣的場景, 比如一個Vue的根實例下面有一個根組件名為App.vue, 它下面有兩個子組件A.vue和B.vue, App.vue想要與A.vue或者B.vue通訊可以通過props傳值的方式, 但是如果A.vue和B.vue之間的通訊就很麻煩了, 他們需要共有的父組件通過自定義事件進行實現(xiàn), A組件想要和B組件通訊往往是這樣的:

- A組件說: "報告老大, 能否幫我托個信給小弟B" => dispatch一個事件給App
- App老大說: "包在我身上, 它需要監(jiān)聽A組件的dispatch的時間, 同時需要broadcast一個事件給B組件"
- B小弟說: "信息已收到", 它需要on監(jiān)聽App組件分發(fā)的事件
這只是一條通訊路徑, 如果父組件下有多個子組件, 子組件之間通訊的路徑就會變的很繁瑣, 父組件需要監(jiān)聽大量的事件, 還需要負責分發(fā)給不同的子組件, 很顯然這并不是我們想要的組件化的開發(fā)體驗.
Vuex就是為了解決這一問題出現(xiàn)的
三.如何引入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)
})
四. Vuex的核心概念?
在介紹Vuex的核心概念之前, 我使用vue-cli初始化了一個demo, 準備以代碼的形式來說明Vuex的核心概念, 大家可以在github上的master分支進行下載.這個demo分別有兩個組件ProductListOne.vue和ProductListTwo.vue, 在App.vue的datat中保存著共有的商品列表, 代碼和初始化的效果如下圖所示:

//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中的公共的狀態(tài), 我是將state看作是所有組件的data, 用于保存所有組件的公共數(shù)據(jù).
- 此時我們就可以把
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的數(shù)據(jù)
}
}
}
//ProductListTwo.vue
export default {
data () {
return {
products: this.$store.state.products //獲取store中state的數(shù)據(jù)
}
}
}
-
此時的頁面如下圖所示, 可以看到, 將公共數(shù)據(jù)抽離出來后, 頁面沒有發(fā)生變化.
state效果
到此處的Github倉庫中代碼為: 分支code01
核心概念2: Getters
我將getters屬性理解為所有組件的computed屬性, 也就是計算屬性. vuex的官方文檔也是說到可以將getter理解為store的計算屬性, getters的返回值會根據(jù)它的依賴被緩存起來,且只有當它的依賴值發(fā)生了改變才會被重新計算。
- 此時,我們可以在
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
}
}
}
- 現(xiàn)在的頁面中,Product List One中的每項商品的價格都減少了一半

到此處的Github倉庫中代碼為: 分支code02
核心概念3: Mutations
我將mutaions理解為store中的methods, mutations對象中保存著更改數(shù)據(jù)的回調函數(shù),該函數(shù)名官方規(guī)定叫type, 第一個參數(shù)是state, 第二參數(shù)是payload, 也就是自定義的參數(shù).
- 下面,我們在
main.js中添加mutations屬性,其中minusPrice這個回調函數(shù)用于將商品的價格減少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中添加一個按鈕,為其添加一個點擊事件, 給點擊事件觸發(fā)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這個回調函數(shù)
注意:調用mutaions中回調函數(shù), 只能使用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
}
}
}
-
添加按鈕, 可以發(fā)現(xiàn), Product List Two中的價格減少了2, 當然你可以自定義
payload,以此自定義減少對應的價格.mutations效果
(Product List One中的價格沒有發(fā)生變化,原因是getter 監(jiān)聽的是map方法產生的新對象)
到此處的Github倉庫中代碼為: 分支code03
核心概念4: Actions
actions 類似于 mutations,不同在于:
actions提交的是mutations而不是直接變更狀態(tài)actions中可以包含異步操作,mutations中絕對不允許出現(xiàn)異步actions中的回調函數(shù)的第一個參數(shù)是context, 是一個與store實例具有相同屬性和方法的對象此時,我們在
store中添加actions屬性, 其中minusPriceAsync采用setTimeout來模擬異步操作,延遲2s執(zhí)行 該方法用于異步改變我們剛才在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中添加一個按鈕,為其添加一個點擊事件, 給點擊事件觸發(fā)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這個回調函數(shù)
export default {
data () {
return {
products: this.$store.state.products
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2);
},
minusPriceAsync() {
this.$store.dispatch('minusPriceAsync', 5); //分發(fā)actions中的minusPriceAsync這個異步函數(shù)
}
}
}
-
添加按鈕, 可以發(fā)現(xiàn), Product List Two中的價格延遲2s后減少了5
actions效果
到此處的Github倉庫中代碼為: 分支code04
核心概念5: Modules
由于使用單一狀態(tài)樹,應用的所有狀態(tài)會集中到一個比較大的對象。當應用變得非常復雜時,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 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)
【相關鏈接】
- 本文代碼地址: https://github.com/Lee-Tanghui/Vuex-Demo
- Vuex官方文檔: https://vuex.vuejs.org/zh-cn/intro.html
- Vuex官方案例演示源碼: https://github.com/vuejs/vuex/tree/dev/examples


