Vuex

在 Vue.js 的項(xiàng)目中,如果項(xiàng)目結(jié)構(gòu)簡單, 父子組件之間的數(shù)據(jù)傳遞可以使用 props 或者 $emit 等方式.
但是如果是大型項(xiàng)目,很多時候都需要在子組件之間傳遞數(shù)據(jù),使用之前的方式就不太方便。Vue 的狀態(tài)管理工具 [Vuex] 完美的解決了這個問題。
什么是Vuex?
官方說法:Vuex 是一個專為 Vue.js應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。
個人理解:Vuex是用來管理組件之間通信的一個插件。
安裝并引入 Vuex
首先,安裝 Vuex:

npm install vuex

其次在 src 目錄下,我創(chuàng)建了名為 store 的目錄 ( 這是一種選擇,你也可以在同級目錄創(chuàng)建一個 store.js 文件 ),再在其中創(chuàng)建一個名為 index.js的文件。
index.js中初始化設(shè)置如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //聲明數(shù)據(jù)
        name:'helloVueX'   
    },
})

main.js 文件中,我們將執(zhí)行以下更新

import Vue from 'vue'
import App from './App'
import store from './store'
new Vue({
  el: '#app',
  store:store,  //store:store 和router一樣,將我們創(chuàng)建的Vuex實(shí)例掛載到這個vue實(shí)例中
  components: { App },
  template: '<App/>'
})

在組件中使用Vuex
例如在App.vue中,我們要將state中定義的name拿來在h1標(biāo)簽中顯示

<template>
    <div id='app'>
        name:
        <h1>{{ $store.state.name }}</h1>
    </div>
</template>

或者要在組件方法中使用

methods:{
    add(){
      console.log(this.$store.state.name)
    }
},

VueX中的核心內(nèi)容
在VueX對象中,其實(shí)不止有state,還有用來操作state中數(shù)據(jù)的方法集,以及當(dāng)我們需要對state中的數(shù)據(jù)需要加工的方法集等等成員。
state 是存放狀態(tài) 和 Vue 實(shí)例中的 data 遵循相同的規(guī)則
使用如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //聲明數(shù)據(jù)
        str:'',
        obj:{},
        arr:[],
        num:0,
        bool:true/false
    },
})

getters 是加工state成員給外界 ,可以認(rèn)為是 store 的計算屬性。getter 的返回值會根據(jù)它的依賴被緩存起來,且只有當(dāng)它的依賴值發(fā)生了改變才會被重新計算。
使用方法如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //聲明數(shù)據(jù)
        shopCar:[]  
    },
getters:{ //可以認(rèn)為是 store 的計算屬性
        shopCarPrices(state){
            var sum=0
            for(var i=0;i<state.shopCar.length;i++){
                sum+=state.shopCar[i]
            }
            return sum
        }
    }
})

組件中調(diào)用

this.$store.getters.shopCarPrices

mutations是對 state成員操作 , Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation。
使用方法如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //聲明數(shù)據(jù)
       name:'helloVueX'   
   },
mutations:{
       amend(state){
           state.name = 'jack'
       }
   }
})

而在組件中,我們需要這樣去調(diào)用這個mutation——例如在App.vue的某個method中:

this.$store.commit('amend')

Mutation傳值
單個值提交時:

this.$store.commit('amend',15)

多個提交時:

this.$store.commit('amend',{age:15,sex:'男'})

接收掛載的參數(shù):

  amend(state,val){
         state.name = 'jack'
         console.log(val) // 15或{age:15,sex:'男'}
        }

actions 是用來專門進(jìn)行異步操作,最終提交mutation方法。
由于setTimeout是異步操作,所以需要使用actions

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ 
       key:''
    },
mutations: {
    updateKey(state,val){
        state.key=val
        console.log(state.key);
    }
  },
actions:{
    updateKey(state,val){
        setTimeout(()=>{
            state.commit('updateKey',val)
        },10)
    }
  }
})

在組件中調(diào)用:

this.$store.dispatch('updateKey',10)

modules 模塊化狀態(tài)管理,每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進(jìn)行同樣方式的分割。當(dāng)項(xiàng)目龐大,狀態(tài)非常多時,可以采用模塊化管理模式。
在創(chuàng)建的store文件夾中在創(chuàng)建一個a.js文件。
在store中的index.js文件中引入剛創(chuàng)建好的a.js文件

import a  from './a'

在index文件中寫入

 modules:{
        a:a
    },

創(chuàng)建好的a.js文件中寫入模塊,可以寫如我們需要的核心對象,語法都是一樣的
比如:

export default {
    state:{
           username :""
    },
    mutations:{
           add(state,val){
           state.username = val
        },
    },
}

組件中傳值

 this.$store.commit('add',res) 
  this.$store.commit('方法名',值) 

組件中調(diào)用

this.$store.state.a.username 
a代表的是在這個a模塊里 
username 代表的是在a這個模塊的state中有一個叫username 的變量

plugins是在vue中使用一些插件 列如可以使用vuex-localstorage
vuex-localstorage 要先進(jìn)行下載 可以使用

npm install vuex-localstorage
cnpm install vuex-localstorage

index.js中引入 vuex-localstorage

import createPersist from 'vuex-localstorage'

使用方法如下:

plugins:[
        createPersist({namespace:"namespace-for-state"})
],
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容