Vuex是什么
- 狀態(tài)管理模式毯焕,將所有組件需要共享的變量全部存儲在一個對象里,然后將這個對象放在頂層組件中供其他組件使用磺樱。
Vuex內(nèi)容
-
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ù)默認(rèn)是state轧坎。外部調(diào)用方式:store.commit('SET_TOKEN', 2187)宏邮。和vue中的methods類似;
-
actions
: 和mutations類似。不過actions支持異步操作眶根。第一個參數(shù)默認(rèn)是和store具有相同參數(shù)屬性的對象蜀铲。外部調(diào)用方式:store.dispatch('nameAsyn');
-
modules
:store的子模塊,內(nèi)容就相當(dāng)于是store的一個實例属百。調(diào)用方式和前面介紹的相似记劝,只是要加上當(dāng)前子模塊名,如:store.a.getters.xxx()
族扰。
Vuex使用
- 開發(fā)中一般使用腳手架vue-cli來搭建項目暴匠,vuex的使用如下:
├── 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.js
示例
/*
* 全局存儲狀態(tài)
*/
const state = {
token: '',
expTime: '',
availableQutoa: 0,
creditQutoa: 0,
}
export default state;
getters.js
示例(我們一般使用getters來獲取state的狀態(tài)娱两,而不是直接使用state):
/*
* 派生狀態(tài),即set、get中的get; 使用getters來獲取state的狀態(tài)
*/
export const token = (state) => {
return state.token;
}
export const expTime = (state) => {
return state.expTime;
}
export const availableQutoa = (state) => {
return state.availableQutoa;
}
export const creditQutoa = (state) => {
return state.creditQutoa;
}
mutation-type.js
示例(我們會將所有mutations的函數(shù)名放在這個文件里)
/*
* 將所有mutations的函數(shù)名放在這個文件里(官方推薦mutions方法名使用大寫)
*/
export const SET_TOKEN = 'SET_TOKEN';
export const SET_EXPTIME = 'SET_EXPTIME';
export const SET_AVAILABLEQUTOA = 'SET_AVAILABLEQUTOA';
export const SET_CREDITQUTOA = 'SET_CREDITQUTOA'
mutations.js示例:
/*
* 提交狀態(tài)修改啦辐,即set涡拘、get中的set; 是Vuex中唯一修改state的方式 不支持異步操作
*/
import * as types from './mutation-types';
export default {
[types.SET_TOKEN](state,token) {
state.token = token;
},
[types.SET_EXPTIME](state,expTime) {
state.expTime = expTime;
},
[types.SET_AVAILABLEQUTOA](state,availableQutoa) {
state.availableQutoa = availableQutoa;
},
[types.SET_CREDITQUTOA](state,creditQutoa) {
state.creditQutoa = creditQutoa;
}
}
actions.js
示例(異步操作)
import * as types from './mutation-types.js'
export default {
tokenAsyn({commit}, {token}) {
commit(types.SET_TOKEN, token); //修改token
},
expTimeAsyn({commit}, {expTime}) {
commit(types.SET_EXPTIME, expTime); //修改token過期時間
},
availableQutoaAsyn({commit},{availableQutoa}) {
commit(types.SET_AVAILABLEQUTOA,availableQutoa) //修改可借額度
},
creditQutoaAsyn({commit},{creditQutoa}) {
commit(types.SET_CREDITQUTOA,creditQutoa) //修改授信額度
},
};
模塊的使用modules--m1.js
示例
const m1 = {
state: {},
getters: {},
mutations: {},
actions: {}
};
export default m1;
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 === 'development' // 開發(fā)環(huán)境中為true换衬,否則為false
export default new Vuex.Store({
state,
getters,
mutations,
actions,
module: {
m1: m1,
m2: m2,
}
plugins: debug ? [createLogger()] : [] //開發(fā)環(huán)境下顯示vuex的狀態(tài)修改
})
store實例掛載到main.js里面的vue上
import store from './store/index.js'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
在vue組件中使用時炸卑,我們通常會使用mapGetters
、mapActions
录豺、mapMutations
朦肘,然后就可以按照vue調(diào)用methods和computed的方式去調(diào)用這些變量或函數(shù),示例如下:
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters([
'token', //包銀項目token
'expTime', //token過期時間
])
},
methods: {
...mapActions([
'tokenAsyn',
'expTimeAsyn',
]),
//獲取包銀項目token
_requestBsbToken() {
let config = {
contentType : 'application/x-www-form-urlencoded',
showWait: false,
}
requestBsbToken({},config).then(res => {
let {code,msg,result} = res;
if(200 !== code) {
Toast(msg);
return;
}
let token = result['access_token'],
saveToen = token.split('.').slice(1,2).join(''),
userInfo = JSON.parse(Base64.decode(saveToen)),
expTime = userInfo['exp'];
this.tokenAsyn({token}); //修改token
this.expTimeAsyn({expTime}) //修改token過期時間
this._queryCredit();
}).catch(error => {
console.log(error)
})
},
}
}
在外部JS文件中使用
import store from '../store/index.js'
let token = store.state.token || ''; //獲取
store.dispatch('expTimeAsyn',{expTime}) //改變