一文讓你徹底搞懂Vuex,滿滿的干貨
官方解釋:Vuex 是專為 vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。
一、Vuex 是做什么呢?
什么是狀態(tài)管理?
簡(jiǎn)單地講:可以把多個(gè)組件都需要的變量全部存儲(chǔ)到一個(gè)對(duì)象里面,然后這個(gè)對(duì)象放在頂層的 vue 實(shí)例中,讓其他組件可以使用。這樣多個(gè)組件就可以共享這個(gè)對(duì)象中的所有屬性。
有些同學(xué)想著,這么簡(jiǎn)單我們自己在vue頂層定義一個(gè)對(duì)象不就可以實(shí)現(xiàn)共享了?我們發(fā)現(xiàn)雖然數(shù)據(jù)可以獲取到,但是如果在某個(gè)組件內(nèi),數(shù)據(jù)改變了,那我們?nèi)绾涡薷臄?shù)據(jù),讓此數(shù)據(jù)在其他組件內(nèi)保持最新呢?
我們的vuex就是為了提供一個(gè)在多個(gè)組件間共享狀態(tài)的插件,而且能夠?qū)崿F(xiàn)實(shí)時(shí)響應(yīng)。
二、Vuex 使用
vuex 是管理組件之間通信的一個(gè)插件,所以使用之前必須安裝。
2.1、安裝
1)使用 script 方式引入
- <script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
2)使用包管理
- npm install vuex --save //yarn add vuex
注意:vuex 必須依賴 vue 使用
2.2、搭建 store 實(shí)例
創(chuàng)建一個(gè) store 文件夾,新建 index.js
- import Vue from "vue";
- import Vuex from "vuex";
- Vue.use(Vuex);//使用vuex
- export default new Vuex.Store({
- state:{},
- mutations:{},
- getters:{},
- actions:{},
- modules:{}
- })
在 main.js 處,掛載 store
- import store from './store'
- new Vue({
- router,
- render: h=>h(App)
- })
- //相當(dāng)于
- // Vue.prototype.$store = store
2.3、使用狀態(tài)
- // store 中定義狀態(tài)
- state:{
- statue: '在線'
- }
- //在組件內(nèi)使用
- <div>組件內(nèi)數(shù)據(jù):{{ $store.state.status }} </div>
- //在 js 中使用
- mounted(){
- console.log( this.$store.state.status )
- }
三、Vuex 的五大核心
3.1、state
state 存放 vuex 的基本數(shù)據(jù),用來存儲(chǔ)變量的。
單一狀態(tài)樹
Vuex 使用單一狀態(tài)樹,即用一個(gè)對(duì)象就包含了全部的狀態(tài)數(shù)據(jù)。state 作為構(gòu)造器選項(xiàng),定義了所有我們需要的基本狀態(tài)參數(shù)。
在組件中引用 state 數(shù)據(jù)方式:
1)通過 vue 的 computed 獲取 vuex 的 state
- export default new Vuex.Store({
- state:{
- online:true
- }
- })
- computed:{
- status(){
- return this.$store.state.online
- }
- }
store 中的數(shù)據(jù)發(fā)生改變時(shí),都會(huì)重新求取計(jì)算屬性,并更新相關(guān) DOM。
2)如果需要使用多個(gè)參數(shù)時(shí),都使用 computed 計(jì)算屬性,就會(huì)使代碼變的有些冗余和復(fù)雜,此時(shí)我們就可以借助 mapState 輔助函數(shù)。
- //state 中數(shù)據(jù)比較多,引用到一個(gè)組件內(nèi)
- export default new Vuex.Store({
- state:{
- online:true,
- per:[
- {name:'qq',age:18}
- ],
- role:'管理員'
- }
- })
- //組件內(nèi)
- import { mapState } from 'vuex'
- export default {
- name: 'App',
- computed: mapState({
- online: state => state.online,
- per: 'per', // 'per'就相當(dāng)于 state.per
- role: 'role' // 'role'就相當(dāng)于 state.role
- })
- }
vuex 使用單一狀態(tài)樹來管理應(yīng)用層級(jí)的全部狀態(tài),單一狀態(tài)樹能夠讓我們最直接的方式找到某個(gè)狀態(tài)的片段,而且之后的維護(hù)和調(diào)試過程,也可以非常方便管理和維護(hù)。
3.2、getters
從 store 中獲取一些 state 變異后的狀態(tài)。
使用的時(shí)候一般有兩種方式:
1)返回的結(jié)果只依賴于 state 中的數(shù)據(jù)
- export default new Vuex.Store({
- state:{
- count:2,
- },
- getters:{
- //返回 count 的 2 倍數(shù)據(jù)
- countDouble(state){
- return state.count*2
- }
- }
- })
- //組件中引用
- <div> 獲取countDouble:{{ $store.getters.countDouble }} </div>
- //運(yùn)行結(jié)果
- 獲取countDouble:4
此處,$store.getters.countDouble 的使用與上邊的 $store.state.count 是一樣的。
2)getters 中返回的變異結(jié)果,依賴于某個(gè) getters 中屬性返回結(jié)果
- export default new Vuex.Store({
- state:{
- count:2,
- },
- getters:{
- //返回 count 的 2 倍數(shù)據(jù)
- countDouble( state ){
- return state.count * 2
- }
- //返回 countDouble 的 2 倍數(shù)據(jù)
- countDoubleT( state , getters ){
- return getters.countDouble * 2
- }
- }
- })
- //組件中引用
- <div> 獲取countDouble:{{ $store.getters.countDoubleT }} </div>
- //運(yùn)行結(jié)果
- 獲取countDouble:8
3.3、mutations
vuex 的store 狀態(tài)的更新唯一方式:提交 Mutation。
Mutations 主要包括兩部分:
字符串的事件類型
一個(gè)回調(diào)函數(shù),該回調(diào)函數(shù)的第一個(gè)參數(shù)就是 state。
1)mutation 中的方法通過 commit 調(diào)用,不傳參數(shù)使用:
- export default new Vuex.Store({
- state:{
- count:2,
- },
- mutations:{
- incrs(state){
- // count 加 1
- state.count++
- }
- }
- })
- //組件調(diào)用
- <button @click=" $store.commit('incrs') " >+</button>
- {{$store.state.count}}
按鈕每點(diǎn)一次,count 就會(huì)自加一次。
2)mutations 傳遞參數(shù)
我們點(diǎn)擊加按鈕時(shí),指定每次點(diǎn)擊增加的數(shù)值,如下:
- export default new Vuex.Store({
- state:{
- count:2,
- },
- mutations:{
- addNum( state,n ){
- // count 加 1
- state.count +=n
- }
- }
- })
- //組件調(diào)用
- <button @click=" $store.addNum( 'incrs' , 5 ) " >+</button>
- {{$store.state.count}}
- //運(yùn)行結(jié)果
- 每點(diǎn)一次按鈕,count 增加 5
上個(gè)實(shí)例傳遞的是一個(gè)參數(shù),如果我們需要傳遞多個(gè)參數(shù)時(shí),該如何實(shí)現(xiàn)呢?
3)mutations 傳遞多個(gè)參數(shù)
- export default new Vuex.Store({
- state:{
- count:2,
- },
- mutations:{
- addNum(state,payload){
- // payload 是傳遞過來的參數(shù)對(duì)象
- state.count += payload.count
- }
- }
- })
- //組件調(diào)用
- <button @click="addTen" >加10</button>
- {{$store.state.count}}
- export default{
- methods:{
- addTen(){
- this.$store.commit({
- type:'addNum',
- count:10,
- ...//可以傳任意多個(gè)參數(shù)
- })
- }
- }
- }
- //運(yùn)行結(jié)果
- 每點(diǎn)一次按鈕,count 增加 10
上述方法是 mutations 特殊的提交封裝。包含了 type 屬性的對(duì)象,將整個(gè) commit 的對(duì)象作為 payload 使用。
3.4、actions
mutations 提交更新數(shù)據(jù)的方法,必須是同步的,如果是異步使用就會(huì)出現(xiàn)問題,然后在項(xiàng)目開發(fā)中往往就會(huì)用到異步更新,比如網(wǎng)路請(qǐng)求數(shù)據(jù)。
actions 是類似于 mutation,功能大致相同,但是 actions 是用來替代 mutations 進(jìn)行異步操作的。
1)actions 的基本使用
- actions:{
- aUpdateCount(context){
- setTimeout(()=>{ //使用定時(shí)器模擬異步操作
- context.commit('updateCount')
- },2000)
- }
- },
- mutations:{
- updateCount(state){
- state.count = 5201314
- },
- }
- // 組件內(nèi)使用
- {{$store.state.count}}
- <button @click="$store.dispatch('aUpdateCount')">異步更新count</button>
- //運(yùn)行結(jié)果
- 點(diǎn)擊按鈕,兩秒后更新 count 值為5201314
值得注意的是,使用 actions 異步更新數(shù)據(jù)的時(shí)候,還是需要經(jīng)過 mutations 中的方法,state 中的數(shù)據(jù)只能由 mutations 中的方法修改。
調(diào)用 mutations 中的方法,使用 commit 調(diào)用。
調(diào)用 actions 中的方法,使用 dispatch 調(diào)用。
2)異步更新的時(shí)候,也可以帶參數(shù)
- // 功能:點(diǎn)擊按鈕,指定 count 修改的值
- actions:{
- aUpdateCount( context, payload ){
- setTimeout(()=>{ //使用定時(shí)器模擬異步操作
- context.commit( 'updateCount' , payload )
- },2000)
- }
- },
- mutations:{
- updateCount( state , payload ){
- state.count = payload
- },
- }
- // 組件內(nèi)使用
- {{$store.state.count}}
- <button @click="$store.dispatch( 'aUpdateCount', '我愛前端' )">異步更新count</button>
- //運(yùn)行結(jié)果
- 點(diǎn)擊按鈕,兩秒后更新 count 值為: 我愛前端
3)傳入異步參數(shù)
- actions:{
- //傳入promise
- updateData(context,payload){
- return new Promise((resolve,reject)=>{
- setTimeout(()=>{
- resolve('我學(xué)會(huì)了')
- },2000)
- })
- },
- }
- //組件內(nèi)調(diào)用
- <button @click="ok">promise執(zhí)行成功,返回"我學(xué)會(huì)了"</button>
- methods:{
- ok(){
- this.$store.dispatch('updateData').then((res)=>{
- console.log(res)
- })
- },
- }
- //運(yùn)行結(jié)果
- 點(diǎn)擊按鈕,兩秒后打?。何覍W(xué)會(huì)了
3.5、modules
modules 是模塊的意思,vue 使用單一狀態(tài)樹,項(xiàng)目越來越大,store 中的數(shù)據(jù)越來越多,不便于數(shù)據(jù)的管理和維護(hù),代碼也會(huì)變得臃腫。因此使用 modules ,把數(shù)據(jù)劃分到對(duì)應(yīng)的某個(gè)模塊,既便于開發(fā),也提高代碼的可讀性。
1)modules 簡(jiǎn)單使用
- import Vue from 'vue'
- import Vuex from 'vuex'
- import { Increase } from './mutation_type.js'
- Vue.use(Vuex)
- export default new Vuex.Store({
- state: {},
- actions: {},
- getters: { },
- mutations: { },
- modules:{
- a:{
- state:{},
- getters:{},
- mutations:{},
- actions:{}
- },
- b:{
- state:{},
- getters:{},
- mutations:{},
- actions:{}
- }
- },
- })
- //也可以整理為
- const moduleA = {
- state:{},
- getters:{},
- mutations:{},
- actions:{}
- }
- const moduleB = {
- state:{},
- getters:{},
- mutations:{},
- actions:{}
- }
- Vue.use(Vuex)
- export default new Vuex.Store({
- state: {},
- actions: {},
- getters: { },
- mutations: { },
- modules:{
- a: moduleA,
- b: moduleB
- },
- })
2)模塊中的數(shù)據(jù)如何使用呢?
- const moduleA = {
- state:{
- aName:'我是模塊a的數(shù)據(jù)'
- },
- getters:{},
- mutations:{},
- actions:{}
- }
- // 組件內(nèi)引用
- {{ $store.state.a.aName }}
3)調(diào)用模塊內(nèi)的 mutations 中的方法,如何調(diào)用呢?
- $store.commit('aChangeName')
調(diào)取模塊內(nèi)的 mutations 中的方法,與之前是一模一樣的,程序會(huì)先從第一層 store 中查找方法,找不到方法時(shí)會(huì)繼續(xù)去模塊中查找。
4)調(diào)用模塊內(nèi)的 getters 內(nèi)方法
- $store.getters.getName
需要注意的是,getters 中方法都是對(duì) state 中數(shù)據(jù)變異,如果模塊的 getters 方法需要根 store 中的 state 呢?
- getName(state,getters , rootState){
- // state 表示當(dāng)前模塊的 state
- // getters表示當(dāng)前模塊的getters
- //rootState 表示根 store 內(nèi)的state
- }
5)模塊內(nèi)的 actions 中的方法,使用 commit 調(diào)用 mutations 中方法時(shí),只能調(diào)用本模塊內(nèi)的 mutations 方法,不能調(diào)用外層的。
四、Vuex 數(shù)據(jù)響應(yīng)原理
Vuex 的 store 中的 state 是響應(yīng)式的,當(dāng) state 中數(shù)據(jù)發(fā)生改變時(shí),vue 組件會(huì)自動(dòng)更新。這就要求我們必須遵守一些vuex對(duì)應(yīng)的規(guī)則:
提前在 store 中初始化好所需的屬性。
說人話,就是必須在state中定義的屬性才能做到響應(yīng)式,如果是后加或刪除的,無法做到響應(yīng)式。
舉個(gè)栗子:
- mutations:{
- changeName(state){
- state.info.name = '愛學(xué)習(xí)的前端人'
- },
- addAdrs(state){
- state.info['address'] = "陜西西安"
- },
- }
- {{this.$store.state.info}}
- <button @click="$store.commit('changeName')">修改姓名</button>
- <button @click="$store.commit('addAdrs')">增加地址</button>
此時(shí)點(diǎn)擊修改姓名的時(shí)候,可以做到響應(yīng)式,而點(diǎn)擊“增加地址”按鈕時(shí),頁(yè)面沒有任何反應(yīng),但是在開發(fā)者模式中可以看到數(shù)據(jù)有變化。
我們要響應(yīng)式,該如何實(shí)現(xiàn)呢?
- addAdrs(state){
- state.info['address'] = "陜西西安"
- //修改為:
- Vue.set(state.info,'address','陜西西安')
- },
同樣的如果要?jiǎng)h除 age 屬性時(shí),使用 delete 也做不到響應(yīng)式,需要修改為 Vue.delete。
實(shí)例:響應(yīng)式刪除 age 屬性
- deleteAge(state){
- //delete state.info.age
- //修改為
- Vue.delete(state.info,'age')
- },
- //組件內(nèi)容
- {{this.$store.state.info}}
- <button @click="$store.commit('deleteAge')">刪除年齡</button>
五、類型常量
在 mutation 中定義很多事件類型,也就是方法名。當(dāng)項(xiàng)目越來越大時(shí),Vuex 管理的狀態(tài)越來越多,需要更新狀態(tài)的情況越來越多,那么意為著 Mutations 中的方法名越來越多,方法過多時(shí),使用的時(shí)候需要花費(fèi)大量精力去記住或來回切換文件找方法名,這樣很容易出錯(cuò),所以推薦大家使用一個(gè)常量,即使方法名出錯(cuò)了,也會(huì)將錯(cuò)就錯(cuò),程序并不會(huì)發(fā)生異常。
如:
- // 新建 mutation_type.js 文件
- //導(dǎo)出一個(gè)常量
- export const Increase = 'increase'
- // store.js文件
- import Vue from 'vue'
- import Vuex from 'vuex'
- import { Increase } from './mutation_type.js'
- Vue.use(Vuex)
- export default new Vuex.Store({
- state:{
- count:2,
- },
- mutations:{
- [Increase](state){
- state.count++
- },
- }
- })
- //組件內(nèi)容
- {{ $store.state.count }}
- <button @click="add">加10</button>
- import { Increase } from './store/mutation_type'
- sxport default{
- methods:{
- add(){
- this.$store.commit(Increase)
- }
- }
- }
使用的時(shí)候,只需要記住 Increase 或者在 mutation_type.js 文件內(nèi)查找就好了。