Vue.js——十分鐘入門(mén)Vuex

2021-8-25    前端達(dá)人

一. 什么是Vuex?

Vuex

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

Vuex核心
Vuex核心

上圖中綠色虛線包裹起來(lái)的部分就是Vuex的核心, state中保存的就是公共狀態(tài), 改變state的唯一方式就是通過(guò)mutations進(jìn)行更改. 可能你現(xiàn)在看這張圖有點(diǎn)不明白, 等經(jīng)過(guò)本文的解釋和案例演示, 再回來(lái)看這張圖, 相信你會(huì)有更好的理解.

二. 為什么要使用Vuex?

試想這樣的場(chǎng)景, 比如一個(gè)Vue的根實(shí)例下面有一個(gè)根組件名為App.vue, 它下面有兩個(gè)子組件A.vueB.vue, App.vue想要與A.vue或者B.vue通訊可以通過(guò)props傳值的方式, 但是如果A.vueB.vue之間的通訊就很麻煩了, 他們需要共有的父組件通過(guò)自定義事件進(jìn)行實(shí)現(xiàn), A組件想要和B組件通訊往往是這樣的:

組件通訊
組件通訊
  • A組件說(shuō): "報(bào)告老大, 能否幫我托個(gè)信給小弟B" => dispatch一個(gè)事件給App
  • App老大說(shuō): "包在我身上, 它需要監(jiān)聽(tīng)A組件的dispatch的時(shí)間, 同時(shí)需要broadcast一個(gè)事件給B組件"
  • B小弟說(shuō): "信息已收到", 它需要on監(jiān)聽(tīng)App組件分發(fā)的事件

這只是一條通訊路徑, 如果父組件下有多個(gè)子組件, 子組件之間通訊的路徑就會(huì)變的很繁瑣, 父組件需要監(jiān)聽(tīng)大量的事件, 還需要負(fù)責(zé)分發(fā)給不同的子組件, 很顯然這并不是我們想要的組件化的開(kāi)發(fā)體驗(yàn).

Vuex就是為了解決這一問(wèn)題出現(xiàn)的

三.如何引入Vuex?

  1. 下載vuex: npm install vuex --save
  2. 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初始化了一個(gè)demo, 準(zhǔn)備以代碼的形式來(lái)說(shuō)明Vuex的核心概念, 大家可以在github上的master分支進(jìn)行下載.這個(gè)demo分別有兩個(gè)組件ProductListOne.vueProductListTwo.vue, 在App.vuedatat中保存著共有的商品列表, 代碼和初始化的效果如下圖所示:

初始化效果
初始化效果
//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: '鼠標(biāo)', price: 20}, {name: '鍵盤(pán)', price: 40}, {name: '耳機(jī)', 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ù).

  • 此時(shí)我們就可以把App.vue中的兩個(gè)組件共同使用的data抽離出來(lái), 放到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: '鼠標(biāo)', price: 20}, {name: '鍵盤(pán)', price: 40}, {name: '耳機(jī)', price: 60}, {name: '顯示屏', price: 80} ] } }) new Vue({ el: '#app', store, render: h => h(App) }) 
  • 此時(shí),ProductListOne.vueProductListTwo.vue也需要做相應(yīng)的更改
//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í)的頁(yè)面如下圖所示, 可以看到, 將公共數(shù)據(jù)抽離出來(lái)后, 頁(yè)面沒(méi)有發(fā)生變化.


    state效果
    state效果

到此處的Github倉(cāng)庫(kù)中代碼為: 分支code01

核心概念2: Getters

我將getters屬性理解為所有組件的computed屬性, 也就是計(jì)算屬性. vuex的官方文檔也是說(shuō)到可以將getter理解為store的計(jì)算屬性, getters的返回值會(huì)根據(jù)它的依賴被緩存起來(lái),且只有當(dāng)它的依賴值發(fā)生了改變才會(huì)被重新計(jì)算。

  • 此時(shí),我們可以在main.js中添加一個(gè)getters屬性, 其中的saleProducts對(duì)象將state中的價(jià)格減少一半(除以2)
//main.js const store = new Vuex.Store({ state:{ products: [ {name: '鼠標(biāo)', price: 20}, {name: '鍵盤(pán)', price: 40}, {name: '耳機(jī)', 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)在的頁(yè)面中,Product List One中的每項(xiàng)商品的價(jià)格都減少了一半
getters效果
getters效果

到此處的Github倉(cāng)庫(kù)中代碼為: 分支code02

核心概念3: Mutations

我將mutaions理解為store中的methods, mutations對(duì)象中保存著更改數(shù)據(jù)的回調(diào)函數(shù),該函數(shù)名官方規(guī)定叫type, 第一個(gè)參數(shù)是state, 第二參數(shù)是payload, 也就是自定義的參數(shù).

  • 下面,我們?cè)?code>main.js中添加mutations屬性,其中minusPrice這個(gè)回調(diào)函數(shù)用于將商品的價(jià)格減少payload這么多, 代碼如下:
//main.js const store = new Vuex.Store({ state:{ products: [ {name: '鼠標(biāo)', price: 20}, {name: '鍵盤(pán)', price: 40}, {name: '耳機(jī)', 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中添加一個(gè)按鈕,為其添加一個(gè)點(diǎn)擊事件, 給點(diǎn)擊事件觸發(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">減少價(jià)格</button> //添加按鈕 </ul> </div> </template> 
  • ProductListTwo.vue中注冊(cè)minusPrice方法, 在該方法中commitmutations中的minusPrice這個(gè)回調(diào)函數(shù)
    注意:調(diào)用mutaions中回調(diào)函數(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中的價(jià)格減少了2, 當(dāng)然你可以自定義payload,以此自定義減少對(duì)應(yīng)的價(jià)格.
    mutations效果
    mutations效果

(Product List One中的價(jià)格沒(méi)有發(fā)生變化,原因是getter 監(jiān)聽(tīng)的是map方法產(chǎn)生的新對(duì)象)

到此處的Github倉(cāng)庫(kù)中代碼為: 分支code03

核心概念4: Actions

actions 類似于 mutations,不同在于:

  • actions提交的是mutations而不是直接變更狀態(tài)

  • actions中可以包含異步操作, mutations中絕對(duì)不允許出現(xiàn)異步

  • actions中的回調(diào)函數(shù)的第一個(gè)參數(shù)是context, 是一個(gè)與store實(shí)例具有相同屬性和方法的對(duì)象

  • 此時(shí),我們?cè)?code>store中添加actions屬性, 其中minusPriceAsync采用setTimeout來(lái)模擬異步操作,延遲2s執(zhí)行 該方法用于異步改變我們剛才在mutaions中定義的minusPrice

//main.js const store = new Vuex.Store({ state:{ products: [ {name: '鼠標(biāo)', price: 20}, {name: '鍵盤(pán)', price: 40}, {name: '耳機(jī)', 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中添加一個(gè)按鈕,為其添加一個(gè)點(diǎn)擊事件, 給點(diǎn)擊事件觸發(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">減少價(jià)格</button> <button @click="minusPriceAsync">異步減少價(jià)格</button> //添加按鈕 </ul> </div> </template> 
  • ProductListTwo.vue中注冊(cè)minusPriceAsync方法, 在該方法中dispatchactions中的minusPriceAsync這個(gè)回調(diào)函數(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這個(gè)異步函數(shù) } } } 
  • 添加按鈕, 可以發(fā)現(xiàn), Product List Two中的價(jià)格延遲2s后減少了5


    actions效果
    actions效果

到此處的Github倉(cāng)庫(kù)中代碼為: 分支code04

核心概念5: Modules

由于使用單一狀態(tài)樹(shù),應(yīng)用的所有狀態(tài)會(huì)集中到一個(gè)比較大的對(duì)象。當(dāng)應(yīng)用變得非常復(fù)雜時(shí),store 對(duì)象就有可能變得相當(dāng)臃腫。為了解決以上問(wèn)題,Vuex 允許我們將 store 分割成模塊(module)。每個(gè)模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進(jìn)行同樣方式的分割

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) 


作者:EduMedia_熠輝

鏈接:https://www.jianshu.com/p/a804606ad8e9

來(lái)源:簡(jiǎn)書(shū)

著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

藍(lán)藍(lán)設(shè)計(jì)建立了UI設(shè)計(jì)分享群,每天會(huì)分享國(guó)內(nèi)外的一些優(yōu)秀設(shè)計(jì),如果有興趣的話,可以進(jìn)入一起成長(zhǎng)學(xué)習(xí),請(qǐng)掃碼ben_lanlan,報(bào)下信息,會(huì)請(qǐng)您入群。歡迎您加入噢~~希望得到建議咨詢、商務(wù)合作,也請(qǐng)與我們聯(lián)系。

分享此文一切功德,皆悉回向給文章原作者及眾讀者.
免責(zé)聲明:藍(lán)藍(lán)設(shè)計(jì)尊重原作者,文章的版權(quán)歸原作者。如涉及版權(quán)問(wèn)題,請(qǐng)及時(shí)與我們?nèi)〉寐?lián)系,我們立即更正或刪除。

藍(lán)藍(lán)設(shè)計(jì)m.yvirxh.cn )是一家專注而深入的界面設(shè)計(jì)公司,為期望卓越的國(guó)內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 平面設(shè)計(jì)服務(wù)


日歷

鏈接

個(gè)人資料

存檔