瞭解vuex核心概念請移步 https://vuex.vuejs.org/zh/javascript
1、初始vuexhtml
1.1 vuex是什麼前端
那麼先來看看這兩個問題:vue
什麼是vuex?官網說:Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。 按我的通俗理解來講就是:vuex就是用來管理各個組件之間的一些狀態,能夠理解爲這些狀態就是公共(共享)部分。此時任何組件都能從中獲取狀態或者觸發一些行爲事件。java
什麼狀況下用到vuex?官網說:若是您不打算開發大型單頁應用,使用 Vuex 多是繁瑣冗餘的。確實是如此——若是您的應用夠簡單,您最好不要使用 Vuex。一個簡單的 global event bus 就足夠您所需了。可是,若是您須要構建是一箇中大型單頁應用,您極可能會考慮如何更好地在組件外部管理狀態,Vuex 將會成爲天然而然的選擇。vuex
好,那麼如今我就當你是開發一個比較大型的項目,在那些地方會用到vuex呢? 隨着應用的複雜度增長,組件之間傳遞數據或組件的狀態會愈來愈多,舉個例子:當A組件進入B組件(A頁面進入B頁面)的時候,經常須要帶一些參數過去,那麼此時你可能會選擇放在url後面當作參數傳遞過去,若是你不想輕易暴露參數,你有可能先存到session中或者localstorage中,而後進入到第二個頁面的時候再取出來。不錯,這確實是一種解決方法,並且用的很多。但這不是一個好的方法,這時候,你就須要vuex來幫助你了。另外,當你基本瞭解vuex的一些皮毛以後,你會發現vuex管理是基於模塊化的思想,那麼這就對項目後期管理維護很友好了。vue-cli
so,如今你就得來深刻認識一下vuex的核心概念了。下面是我的理解的概念,首先在此以前建議最好先把官方文檔Vuex2.0概念過一遍。session
vuex 就是把須要共享的變量所有存儲在一個對象裏面,而後將這個對象放在頂層組件中供其餘組件使用app
父子組件通訊時,咱們一般會採用 props + emit 這種方式。但當通訊雙方不是父子組件甚至壓根不存在相關聯繫,或者一個狀態須要共享給多個組件時,就會很是麻煩,數據也會至關難維護異步
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 } }
前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力 羣內有大量PDF可供自取,更有乾貨實戰項目視頻。
個就是最基本也是完整的 vuex 代碼; vuex 包含有五個基本的對象
state :存儲狀態。也就是變量;
getters :派生狀態。也就是 set 、 get 中的 get ,有兩個可選參數: state 、 getters 分別能夠獲取 state 中的變量和其餘的 getters 。外部調用方式: store.getters.personInfo() 。就和 vue 的 computed 差很少;
mutations :提交狀態修改。也就是 set 、 get 中的 set ,這是 vuex 中惟一修改 state 的方式,但不支持異步操做。第一個參數默認是 state 。外部調用方式: store.commit('SET_AGE', 18) 。和 vue 中的 methods 相似。
actions :和 mutations 相似。不過 actions 支持異步操做。第一個參數默認是和 store 具備相同參數屬性的對象。外部調用方式: store.dispatch('nameAsyn') 。
modules : store 的子模塊,內容就至關因而 store 的一個實例。調用方式和前面介紹的類似,只是要加上當前子模塊名,如: store.a.getters.xxx()
1.3 vue-cli中使用vuex的方式
目錄結構
├── index.html ├── main.js ├── components └── store ├── index.js # 咱們組裝模塊並導出 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 的狀態,而不是直接使用 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 的函數名放在這個文件裏
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示例
若是不是很複雜的應用,通常來說是不會分模塊的
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'; // 開發環境中爲true,不然爲false export default new vuex.Store({ state, getters, mutations, actions, modules: { m1, m2 }, plugins: debug ? [createLogger()] : [] // 開發環境下顯示vuex的狀態修改 });
最後將 store 實例掛載到 main.js 裏面的 vue 上去就好了
import store from './store/index.js'; new Vue({ el: '#app', store, render: h => h(App) });
在 vue 組件中使用時,咱們一般會使用 mapGetters 、 mapActions 、 mapMutations ,而後就能夠按照 vue 調用 methods 和 computed 的方式去調用這些變量或函數,示例如
import {mapGetters, mapMutations, mapActions} from 'vuex'; /* 只寫組件中的script部分 */ export default { computed: { ...mapGetters([ name, age ]) }, methods: { ...mapMutations({ setName: 'SET_NAME', setAge: 'SET_AGE' }), ...mapActions([ nameAsyn ]) } };
2、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 裏的代碼應該改爲,在實例化 Vue 對象時加入 store 對象
//vuex import store from './store' new Vue({ el: '#app', router, store,//使用store template: '<App/>', components: { App } })
這樣就把 store 分離出去了 , 那麼還有一個問題是 : 這裏 $store.state.show 不管哪一個組件均可以使用 , 那組件多了以後 , 狀態也多了 , 這麼多狀態都堆在 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 組件的狀態了
export default { state:{ show:false } }
作出這樣的修改以後 , 咱們將以前咱們使用的 $store.state.show
通通改成 $store.state.dialog.show
便可
若是還有其餘的組件須要使用 vuex , 就新建一個對應的狀態文件 , 而後將他們加入 store 文件夾下的 index.js 文件中的 modules 中
modules: { dialog: dialog_store, other: other,//其餘組件 }
3、mutations
對 vuex 的依賴僅僅只有一個 $store.state.dialog.show 一個狀態 , 可是若是咱們要進行一個操做 , 須要依賴不少不少個狀態 , 那管理起來又麻煩了
mutations 裏的操做必須是同步的
export default { state:{//state show:false }, mutations:{ switch_dialog(state){//這裏的state對應着上面這個state state.show = state.show?false:true; //你還能夠在這裏執行其餘的操做改變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') 來觸發 mutations 中的 switch_dialog 方法
4、actions
多個 state 的操做 , 使用 mutations 會來觸發會比較好維護 , 那麼須要執行多個 mutations 就須要用 action 了
export default { state:{//state show:false }, mutations:{ switch_dialog(state){//這裏的state對應着上面這個state state.show = state.show?false:true; //你還能夠在這裏執行其餘的操做改變state } }, actions:{ switch_dialog(context){//這裏的context和咱們使用的$store擁有相同的對象和方法 context.commit('switch_dialog'); //你還能夠在這裏觸發其餘的mutations方法 }, } }
前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力 羣內有大量PDF可供自取,更有乾貨實戰項目視頻。
那麼 , 在以前的父組件中 , 咱們須要作修改 , 來觸發 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') 來觸發 action 中的 switch_dialog 方法。 官方推薦 , 將異步操做放在 action 中
5、getters
getters 和 vue 中的 computed 相似 , 都是用來計算 state 而後生成新的數據 ( 狀態 ) 的
假如咱們須要一個與狀態 show 恰好相反的狀態 , 使用 vue 中的 computed 能夠這樣算出來
computed(){ not_show(){ return !this.$store.state.dialog.show; } }
那麼 , 若是不少不少個組件中都須要用到這個與 show 恰好相反的狀態 , 那麼咱們須要寫不少不少個 not_show , 使用 getters 就能夠解決這種問題
export default { state:{//state show:false }, getters:{ not_show(state){//這裏的state對應着上面這個state return !state.show; } }, mutations:{ switch_dialog(state){//這裏的state對應着上面這個state state.show = state.show?false:true; //你還能夠在這裏執行其餘的操做改變state } }, actions:{ switch_dialog(context){//這裏的context和咱們使用的$store擁有相同的對象和方法 context.commit('switch_dialog'); //你還能夠在這裏觸發其餘的mutations方法 }, } }
咱們在組件中使用 $store.state.dialog.show
來得到狀態 show , 相似的 , 咱們可使用 $store.getters.not_show
來得到狀態 not_show
注意 : $store.getters.not_show
的值是不能直接修改的 , 須要對應的 state 發生變化才能修改
6、mapState、mapGetters、mapActions
不少時候 , $store.state.dialog.show
、 $store.dispatch('switch_dialog')
這種寫法很不方便
使用 mapState 、 mapGetters 、 mapActions 就不會這麼複雜了
<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 中