建一個(gè)做筆記的網(wǎng)站提高工作效率
了解vuex核心概念請(qǐng)移步 https://vuex.vuejs.org/zh/
# 一、初始vuex
# 1.1 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
類似。actions
:和mutations
類似。不過(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名稱(官方推薦mutions方法名使用大寫)├── 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’; // 開發(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
實(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’;
/* 只寫組件中的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ú)寫dialog
組件的狀態(tài)了
export default {
state:{
show:false
}
}
做出這樣的修改之后 , 我們將之前我們使用的
s t o r e . s t a t e . s h o w < / c o d e > 統(tǒng)統(tǒng)改為 < c o d e > store.state.show</code> 統(tǒng)統(tǒng)改為 <code> store.state.show</code>統(tǒng)統(tǒng)改為<code>store.state.dialog.show
即可
- 如果還有其他的組件需要使用
vuex
, 就新建一個(gè)對(duì)應(yīng)的狀態(tài)文件 , 然后將他們加入store
文件夾下的index.js
文件中的modules
中
modules: {
dialog: dialog_store,
other: other,//其他組件
}
# 三、mutations
對(duì)
vuex
的依賴僅僅只有一個(gè)$store.state.dialog.show
一個(gè)狀態(tài) , 但是如果我們要進(jìn)行一個(gè)操作 , 需要依賴很多很多個(gè)狀態(tài) , 那管理起來(lái)又麻煩了
mutations
里的操作必須是同步的
export default {state:{//stateshow:false},mutations:{switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)statestate.show = state.show?false:true;//你還可以在這里執(zhí)行其他的操作改變state}} }
使用
mutations
后 , 原先我們的父組件可以改為
<template><div id="app"><a href="javascript:;" @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:{//stateshow:false},mutations:{switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)statestate.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:;" @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)計(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) , 那么我們需要寫很多很多個(gè)not_show
, 使用getters
就可以解決這種問(wèn)題
export default {state:{//stateshow:false},getters:{not_show(state){//這里的state對(duì)應(yīng)著上面這個(gè)statereturn !state.show;}},mutations:{switch_dialog(state){//這里的state對(duì)應(yīng)著上面這個(gè)statestate.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
, 類似的 , 我們可以使用$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')
這種寫法很不方便
- 使用
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
類似 ,mapGetters
一般也寫在computed
中 ,mapActions
一般寫在methods
中