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

