您好,登錄后才能下訂單哦!
小編給大家分享一下vue狀態(tài)管理模式之vuex如何實(shí)現(xiàn),相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
一、初始vuex
1.1 vuex是什么
那么先來(lái)看看這兩個(gè)問(wèn)題:
什么是vuex?官網(wǎng)說(shuō):Vuex 是一個(gè)專(zhuān)為 Vue.js 應(yīng)用程序開(kāi)發(fā)的狀態(tài)管理模式。 按個(gè)人通俗理解來(lái)說(shuō)就是:vuex就是用來(lái)管理各個(gè)組件之間的一些狀態(tài),可以理解為這些狀態(tài)就是公共(共享)部分。此時(shí)任何組件都能從中獲取狀態(tài)或者觸發(fā)一些行為事件。
什么情況下用到vuex?官網(wǎng)說(shuō):如果您不打算開(kāi)發(fā)大型單頁(yè)應(yīng)用,使用 Vuex 可能是繁瑣冗余的。確實(shí)是如此——如果您的應(yīng)用夠簡(jiǎn)單,您最好不要使用 Vuex。一個(gè)簡(jiǎn)單的 global event bus 就足夠您所需了。但是,如果您需要構(gòu)建是一個(gè)中大型單頁(yè)應(yīng)用,您很可能會(huì)考慮如何更好地在組件外部管理狀態(tài),Vuex 將會(huì)成為自然而然的選擇。
好,那么現(xiàn)在我就當(dāng)你是開(kāi)發(fā)一個(gè)比較大型的項(xiàng)目,在那些地方會(huì)用到vuex呢? 隨著應(yīng)用的復(fù)雜度增加,組件之間傳遞數(shù)據(jù)或組件的狀態(tài)會(huì)越來(lái)越多,舉個(gè)例子:當(dāng)A組件進(jìn)入B組件(A頁(yè)面進(jìn)入B頁(yè)面)的時(shí)候,常常需要帶一些參數(shù)過(guò)去,那么此時(shí)你可能會(huì)選擇放在url后面當(dāng)做參數(shù)傳遞過(guò)去,如果你不想輕易暴露參數(shù),你有可能先存到session中或者localstorage中,然后進(jìn)入到第二個(gè)頁(yè)面的時(shí)候再取出來(lái)。不錯(cuò),這確實(shí)是一種解決方法,而且用的不少。但這不是一個(gè)好的方法,這時(shí)候,你就需要vuex來(lái)幫助你了。另外,當(dāng)你基本了解vuex的一些皮毛之后,你會(huì)發(fā)現(xiàn)vuex管理是基于模塊化的思想,那么這就對(duì)項(xiàng)目后期管理維護(hù)很友好了。
so,現(xiàn)在你就得來(lái)深入認(rèn)識(shí)一下vuex的核心概念了。下面是個(gè)人理解的概念,首先在此之前建議最好先把官方文檔Vuex2.0概念過(guò)一遍。
vuex 就是把需要共享的變量全部存儲(chǔ)在一個(gè)對(duì)象里面,然后將這個(gè)對(duì)象放在頂層組件中供其他組件使用
父子組件通信時(shí),我們通常會(huì)采用 props + emit 這種方式。但當(dāng)通信雙方不是父子組件甚至壓根不存在相關(guān)聯(lián)系,或者一個(gè)狀態(tài)需要共享給多個(gè)組件時(shí),就會(huì)非常麻煩,數(shù)據(jù)也會(huì)相當(dāng)難維護(hù)
1.2 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 } }
個(gè)就是最基本也是完整的 vuex 代碼; vuex 包含有五個(gè)基本的對(duì)象
state :存儲(chǔ)狀態(tài)。也就是變量;
getters :派生狀態(tài)。也就是 set 、 get 中的 get ,有兩個(gè)可選參數(shù): state 、 getters 分別可以獲取 state 中的變量和其他的 getters 。外部調(diào)用方式: store.getters.personInfo() 。就和 vue 的 computed 差不多;
mutations :提交狀態(tài)修改。也就是 set 、 get 中的 set ,這是 vuex 中唯一修改 state 的方式,但不支持異步操作。第一個(gè)參數(shù)默認(rèn)是 state 。外部調(diào)用方式: store.commit('SET_AGE', 18) 。和 vue 中的 methods 類(lèi)似。
actions :和 mutations 類(lèi)似。不過(guò) actions 支持異步操作。第一個(gè)參數(shù)默認(rèn)是和 store 具有相同參數(shù)屬性的對(duì)象。外部調(diào)用方式: store.dispatch('nameAsyn') 。
modules : store 的子模塊,內(nèi)容就相當(dāng)于是 store 的一個(gè)實(shí)例。調(diào)用方式和前面介紹的相似,只是要加上當(dāng)前子模塊名,如: store.a.getters.xxx()
1.3 vue-cli中使用vuex的方式
目錄結(jié)構(gòu)
├── index.html ├── main.js ├── components └── store ├── index.js # 我們組裝模塊并導(dǎo)出 store 的地方 ├── state.js # 跟級(jí)別的 state ├── getters.js # 跟級(jí)別的 getter ├── mutation-types.js # 根級(jí)別的mutations名稱(chēng)(官方推薦mutions方法名使用大寫(xiě)) ├── mutations.js # 根級(jí)別的 mutation ├── actions.js # 根級(jí)別的 action └── modules ├── m1.js # 模塊1 └── m2.js # 模塊2
state示例
const state = { name: 'weish', age: 22 }; export default state;
getter示例
getters.js 示例(我們一般使用 getters 來(lái)獲取 state 的狀態(tài),而不是直接使用 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示例
將所有 mutations 的函數(shù)名放在這個(gè)文件里
export const SET_NAME = 'SET_NAME'; export const SET_AGE = 'SET_AGE';
mutations示例
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示例
異步操作、多個(gè) commit 時(shí)
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示例
如果不是很復(fù)雜的應(yīng)用,一般來(lái)講是不會(huì)分模塊的
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'; // 開(kāi)發(fā)環(huán)境中為true,否則為false export default new vuex.Store({ state, getters, mutations, actions, modules: { m1, m2 }, plugins: debug ? [createLogger()] : [] // 開(kāi)發(fā)環(huán)境下顯示vuex的狀態(tài)修改 });
最后將 store 實(shí)例掛載到 main.js 里面的 vue 上去就行了
import store from './store/index.js'; new Vue({ el: '#app', store, render: h => h(App) });
在 vue 組件中使用時(shí),我們通常會(huì)使用 mapGetters 、 mapActions 、 mapMutations ,然后就可以按照 vue 調(diào)用 methods 和 computed 的方式去調(diào)用這些變量或函數(shù),示例如
import {mapGetters, mapMutations, mapActions} from 'vuex'; /* 只寫(xiě)組件中的script部分 */ export default { computed: { ...mapGetters([ name, age ]) }, methods: { ...mapMutations({ setName: 'SET_NAME', setAge: 'SET_AGE' }), ...mapActions([ nameAsyn ]) } };
二、modules
在 src 目錄下 , 新建一個(gè) store 文件夾 , 然后在里面新建一個(gè) index.js
import Vue from 'vue' import vuex from 'vuex' Vue.use(vuex); export default new vuex.Store({ state:{ show:false } })
在 main.js 里的代碼應(yīng)該改成,在實(shí)例化 Vue 對(duì)象時(shí)加入 store 對(duì)象
//vuex import store from './store' new Vue({ el: '#app', router, store,//使用store template: '<App/>', components: { App } })
這樣就把 store 分離出去了 , 那么還有一個(gè)問(wèn)題是 : 這里 $store.state.show 無(wú)論哪個(gè)組件都可以使用 , 那組件多了之后 , 狀態(tài)也多了 , 這么多狀態(tài)都堆在 store 文件夾下的 index.js 不好維護(hù)怎么辦 ?
我們可以使用 vuex 的 modules , 把 store 文件夾下的 index.js 改成
import Vue from 'vue' import vuex from 'vuex' Vue.use(vuex); import dialog_store from '../components/dialog_store.js';//引入某個(gè)store對(duì)象 export default new vuex.Store({ modules: { dialog: dialog_store } })
這里我們引用了一個(gè) dialog_store.js , 在這個(gè) js 文件里我們就可以單獨(dú)寫(xiě) dialog 組件的狀態(tài)了
export default { state:{ show:false } }
做出這樣的修改之后 , 我們將之前我們使用的 $store.state.show 統(tǒng)統(tǒng)改為 $store.state.dialog.show 即可
如果還有其他的組件需要使用 vuex , 就新建一個(gè)對(duì)應(yīng)的狀態(tài)文件 , 然后將他們加入 store 文件夾下的 index.js 文件中的 modules 中
modules: { dialog: dialog_store, other: other,//其他組件 }
三、mutations
對(duì) vuex 的依賴(lài)僅僅只有一個(gè) $store.state.dialog.show 一個(gè)狀態(tài) , 但是如果我們要進(jìn)行一個(gè)操作 , 需要依賴(lài)很多很多個(gè)狀態(tài) , 那管理起來(lái)又麻煩了
mutations 里的操作必須是同步的
export default { state:{//state show:false }, mutations:{ switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)state state.show = state.show?false:true; //你還可以在這里執(zhí)行其他的操作改變state } } }
使用 mutations 后 , 原先我們的父組件可以改為
<template> <div id="app"> <a href="javascript:;" rel="external nofollow" rel="external nofollow" @click="$store.commit('switch_dialog')">點(diǎn)擊</a> <t-dialog></t-dialog> </div> </template> <script> import dialog from './components/dialog.vue' export default { components:{ "t-dialog":dialog } } </script>
使用 $store.commit('switch_dialog') 來(lái)觸發(fā) mutations 中的 switch_dialog 方法
四、actions
多個(gè) state 的操作 , 使用 mutations 會(huì)來(lái)觸發(fā)會(huì)比較好維護(hù) , 那么需要執(zhí)行多個(gè) mutations 就需要用 action 了
export default { state:{//state show:false }, mutations:{ switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)state state.show = state.show?false:true; //你還可以在這里執(zhí)行其他的操作改變state } }, actions:{ switch_dialog(context){//這里的context和我們使用的$store擁有相同的對(duì)象和方法 context.commit('switch_dialog'); //你還可以在這里觸發(fā)其他的mutations方法 }, } }
那么 , 在之前的父組件中 , 我們需要做修改 , 來(lái)觸發(fā) action 里的 switch_dialog 方法
<template> <div id="app"> <a href="javascript:;" rel="external nofollow" rel="external nofollow" @click="$store.dispatch('switch_dialog')">點(diǎn)擊</a> <t-dialog></t-dialog> </div> </template> <script> import dialog from './components/dialog.vue' export default { components:{ "t-dialog":dialog } } </script>
使用 $store.dispatch('switch_dialog') 來(lái)觸發(fā) action 中的 switch_dialog 方法。
官方推薦 , 將異步操作放在 action 中
五、getters
getters 和 vue 中的 computed 類(lèi)似 , 都是用來(lái)計(jì)算 state 然后生成新的數(shù)據(jù) ( 狀態(tài) ) 的
假如我們需要一個(gè)與狀態(tài) show 剛好相反的狀態(tài) , 使用 vue 中的 computed 可以這樣算出來(lái)
computed(){ not_show(){ return !this.$store.state.dialog.show; } }
那么 , 如果很多很多個(gè)組件中都需要用到這個(gè)與 show 剛好相反的狀態(tài) , 那么我們需要寫(xiě)很多很多個(gè) not_show , 使用 getters 就可以解決這種問(wèn)題
export default { state:{//state show:false }, getters:{ not_show(state){//這里的state對(duì)應(yīng)著上面這個(gè)state return !state.show; } }, mutations:{ switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)state state.show = state.show?false:true; //你還可以在這里執(zhí)行其他的操作改變state } }, actions:{ switch_dialog(context){//這里的context和我們使用的$store擁有相同的對(duì)象和方法 context.commit('switch_dialog'); //你還可以在這里觸發(fā)其他的mutations方法 }, } }
我們?cè)诮M件中使用 $store.state.dialog.show 來(lái)獲得狀態(tài) show , 類(lèi)似的 , 我們可以使用 $store.getters.not_show 來(lái)獲得狀態(tài) not_show
注意 : $store.getters.not_show 的值是不能直接修改的 , 需要對(duì)應(yīng)的 state 發(fā)生變化才能修改
六、mapState、mapGetters、mapActions
很多時(shí)候 , $store.state.dialog.show 、 $store.dispatch('switch_dialog') 這種寫(xiě)法很不方便
使用 mapState 、 mapGetters 、 mapActions 就不會(huì)這么復(fù)雜了
<template> <el-dialog :visible.sync="show"></el-dialog> </template> <script> import {mapState} from 'vuex'; export default { computed:{ //這里的三點(diǎn)叫做 : 擴(kuò)展運(yùn)算符 ...mapState({ show:state=>state.dialog.show }), } } </script>
相當(dāng)于
<template> <el-dialog :visible.sync="show"></el-dialog> </template> <script> import {mapState} from 'vuex'; export default { computed:{ show(){ return this.$store.state.dialog.show; } } } </script>
mapGetters 、 mapActions 和 mapState 類(lèi)似 , mapGetters 一般也寫(xiě)在 computed 中 , mapActions 一般寫(xiě)在 methods 中
以上是“vue狀態(tài)管理模式之vuex如何實(shí)現(xiàn)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。