Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化。簡(jiǎn)單來(lái)說(shuō)就是:應(yīng)用遇到多個(gè)組件共享狀態(tài)時(shí),使用vuex。
VueX 是一個(gè)專門為 Vue.js 應(yīng)用設(shè)計(jì)的狀態(tài)管理構(gòu)架,統(tǒng)一管理和維護(hù)各個(gè)vue組件的可變化狀態(tài)
場(chǎng)景:多個(gè)組件共享數(shù)據(jù)或者是跨組件傳遞數(shù)據(jù)時(shí)
vuex的五個(gè)核心概念:
- State:共享狀態(tài),vuex的基本數(shù)據(jù),用來(lái)存儲(chǔ)變量,相當(dāng)于組件data里的數(shù)據(jù),只不過(guò)此時(shí)變成了全局變量。
- Getter:基于state的派生狀態(tài),相當(dāng)于組件中的computed中的屬性。
- Mutation:更改vuex中store共享狀態(tài)的方法,通過(guò)提交mutation來(lái)去修改狀態(tài),進(jìn)行同步操作數(shù)據(jù),通常用于action獲取異步數(shù)據(jù),獲取通過(guò)commit提交數(shù)據(jù)給mutation,在mutation同步操作state中的數(shù)據(jù)。
- action:支持異步操作,可用于異步獲取請(qǐng)求中的數(shù)據(jù),并將獲取的數(shù)據(jù)同步commit提交給mutation,實(shí)現(xiàn)ajax異步請(qǐng)求數(shù)據(jù),mutation將其數(shù)據(jù)同步到state中。
- modules:模塊化vuex,為了方便后期對(duì)于項(xiàng)目的管理,可以讓每一個(gè)模塊擁有自己的state、mutation、action、getters,使得結(jié)構(gòu)非常清晰,方便管理。
優(yōu)勢(shì)和劣勢(shì)有哪些?
優(yōu)勢(shì)主要就是可以全局共享數(shù)據(jù),方法。方便統(tǒng)一管理
劣勢(shì)的話,頁(yè)面刷新后state的變量都會(huì)還原清空,不會(huì)像cookies一樣持久性存儲(chǔ)
頁(yè)面刷新后vuex的state數(shù)據(jù)丟失怎么解決?
先說(shuō)一下為什么會(huì)丟失呢?
因?yàn)閟tore里的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中的,當(dāng)頁(yè)面刷新時(shí)頁(yè)面會(huì)重新加載vue實(shí)例,store里面的數(shù)據(jù)就會(huì)被重新賦值
如何避免?
其實(shí)主要還是看使用的場(chǎng)景是怎樣的,如果想某些數(shù)據(jù)持久性保留也可以搭配使用cookies或者localStorage。比如一些登錄的信息等。
比如請(qǐng)求拿到了登錄信息后可以先存在localStorage,將state里的變量值和sessionStorage里面的綁定,mutations中修改的時(shí)候同時(shí)修改state和localStorage。最后頁(yè)面直接使用vuex中的變量。
正式進(jìn)入使用
vuex的安裝
打開終端,輸入命令行npm install vuex --save進(jìn)行下載vuex
vuex應(yīng)用核心管理倉(cāng)庫(kù) 構(gòu)建store
這里新建store文件夾,創(chuàng)建一個(gè)js取名為index.js,
在index里 ,通過(guò)將state,mutations,actions,getters引入到store中,并暴露出store對(duì)象。
下面為index.js的代碼
/*
vuex最核心的管理對(duì)象 store
*/
import Vue from 'vue';
import Vuex from 'vuex';
// 分別引入這四個(gè)文件 這四個(gè)文件的內(nèi)容和用法在下面分別講到
import state from './state';
import mutations from './mutations';
import actions from './actions';
import getters from './getters';
//聲明使用插件
Vue.use(Vuex)
//new 一個(gè)Vuex的對(duì)象,將state,mutation,action,getters配置到vuex的store中,方便管理數(shù)據(jù)
export default new Vuex.Store({
state,
mutations,
actions,
getters,
})
掛載store到vue實(shí)例上
main.js中
import store from './store'
// ..........
new Vue({
el: '#app',
router,
store, // ***
render: h => h(App)
})
state狀態(tài)管理數(shù)據(jù)
我們通常將需要進(jìn)行管理的共享數(shù)據(jù),放入state中,使其形似為全局變量,對(duì)于需要的組件進(jìn)行引入該state狀態(tài)數(shù)據(jù)。
const state = {
userId: '',
token: '',
name: '',
avatar: '',
introduction: '',
roles: [],
tenantId: 1,
userInfo: null
};
mutations 同步提交數(shù)據(jù)
mutations用于更改state中的狀態(tài)邏輯的,且為同步更改state中的狀態(tài)數(shù)據(jù)。
需要知道的是在vuex中只能通過(guò)mutation來(lái)去修改state對(duì)象,
可以通過(guò)獲取actions獲取到的數(shù)據(jù)去修改state,也可以在mutations模塊中直接定義方法來(lái)去更改狀態(tài)數(shù)據(jù)。
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token;
},
SET_USERID: (state, userId) => {
state.userId = userId;
},
SET_NAME: (state, name) => {
state.name = name;
},
SET_ROLES: (state, roles) => {
state.roles = roles;
},
SET_TENANTID: (state, roles) => {
state.tenantId = roles;
},
SET_USER_INFO: (state, userInfo) => {
state.userInfo = userInfo;
}
};
通過(guò)mutations和下面的actions模塊,大家也可以看出commit是用于調(diào)用mutation模塊中的。
在組件中調(diào)用其mutation模塊的代碼為:
this.$store.commit('SET_TOKEN', token_data)
actions 的異步操作
actions與其mutations類似,但其可以進(jìn)行異步操作,
且將異步操作獲取的數(shù)據(jù)提交給mutations,使得mutations更改state中的狀態(tài)數(shù)據(jù), 這里常常用于獲取ajax請(qǐng)求中的數(shù)據(jù)(因?yàn)槭钱惒?,并將其獲取的數(shù)據(jù)commit提交給mutations 使得 state數(shù)據(jù)狀態(tài)的更新。
和mutations 的不同之處在于:
- Action 提交的是 mutation,而不是直接變更狀態(tài)。
- Action 可以包含任意異步操作。
舉例
/* 下面就是通過(guò)actions執(zhí)行異步Ajax請(qǐng)求,
得到數(shù)據(jù)后,
通過(guò)commit的方法調(diào)用mutations 從而更新數(shù)據(jù)
例如: commit('SET_TOKEN', data.uuid);
*/
const actions = {
login({ commit }, userInfo) { // 用戶登錄
const params = userInfo;
params.userName = userInfo.userName.trim()
return new Promise((resolve, reject) => {
getLogin(params)
.then((response) => {
const { status, message, data } = response || {};
if (status === 200) {
// 存入 參數(shù): 1.調(diào)用的值 2.所要存入的數(shù)據(jù)
commit('SET_USER_INFO', data);
commit('SET_TOKEN', data.uuid);
commit('SET_USERID', data.id);
commit('SET_ROLES', data.roles);
commit('SET_NAME', data.realName);
commit('SET_TENANTID', data.tenantId || 1);
setToken(data.uuid);
db.save('userInfo', data);
db.save('tenantId', data.tenantId || 1);
localStorage.setItem('loginToken', data.uuid);
resolve(data);
} else {
// ElementUI.Message.error(message); // axios攔截統(tǒng)一提示了
}
})
.catch((error) => {
// ElementUI.Message.error(error.message); // axios攔截統(tǒng)一提示了
reject(error);
});
});
},
}
這個(gè)actions在組件中的調(diào)用方法就是:
this.$store.dispatch('user/login', postUser)
.then(res => {
// .............
})
// 我這里的login方法寫在了user.js這個(gè)module里 所以這里調(diào)用是 user/login
// 下面會(huì)講到module
Getters 對(duì)state進(jìn)行加工
Getters相當(dāng)于computed計(jì)算屬性,用于加工處理state狀態(tài)數(shù)據(jù),有其兩個(gè)默認(rèn)參數(shù),第一個(gè)默認(rèn)參數(shù)為state,第二個(gè)默認(rèn)參數(shù)為getters。
const getters={
plusCount(state){
return state.count + 1
},
//獲取state中狀態(tài)數(shù)據(jù)對(duì)象,和獲取getters模塊中plusCount數(shù)據(jù)
totalCount(state,getters){
return getters.plusCount + state.count
}
}
在組件中調(diào)用該方法的代碼片段為:
this.$store.getters.totalCount()
在Vue組件中獲得Vuex狀態(tài)
從store
實(shí)例中讀取狀態(tài)最簡(jiǎn)單的方法就是在計(jì)算屬性中返回某個(gè)狀態(tài),由于Vuex
的狀態(tài)存儲(chǔ)是響應(yīng)式的,所以在這里每當(dāng)store.state.count
變化的時(shí)候,都會(huì)重新求取計(jì)算屬性,進(jìn)行響應(yīng)式更新。
computed: {
count: function(){
return this.$store.state.count
}
},
那么對(duì)于以上的store我們就簡(jiǎn)單介紹完了,相信大家看完后對(duì)于vuex會(huì)有一定的理解。那么這個(gè)時(shí)候我們要想,是不是使用this.$store.state
或this.$store.getters.xxx
感到麻煩呢?下面我們介紹另一種引入state和getters的方式
輔助函數(shù) mapState 和 mapGetters
對(duì)于上述的在組件中引用state和getters的方法是不是感到麻煩呢?使用mapState你將會(huì)感受到便利。
組件中這樣使用
//首先我們需要先將輔助函數(shù)引入
import { mapGetters,mapState } from 'vuex'
export default {
computed: {
// 使用對(duì)象展開運(yùn)算符將 getter 混入 computed 對(duì)象中
...mapGetters( ['plusCount','totalCount'] )
// 使用對(duì)象展開運(yùn)算符將 state 混入 computed 對(duì)象中
...mapState( ['userInfo','count'] )
},
methods:{
getData(){
// 這里就能直接使用了 直接使用state 和getters里的數(shù)據(jù)
// this.userInfo
// this.plusCount
}
}
}
Module子模塊化管理
store文件夾下的index.js代碼如下
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
const store = new Vuex.Store({
modules,
getters
})
export default store
文件目錄如圖
舉例 api.js
import { getKey, getLogin, logout, getInfo } from '@/api/user';
import { setToken, removeToken } from '@/utils/auth';
import db from '@/utils/localstorage';
import router, { resetRouter } from '@/router';
import ElementUI from 'element-ui';
const state = {
userId: '',
token: '',
name: '',
avatar: '',
introduction: '',
roles: [],
tenantId: 1,
userInfo: null
// roles: ['9999']
};
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token;
},
SET_USERID: (state, userId) => {
state.userId = userId;
},
SET_NAME: (state, name) => {
state.name = name;
},
SET_ROLES: (state, roles) => {
state.roles = roles;
},
SET_TENANTID: (state, roles) => {
state.tenantId = roles;
},
SET_USER_INFO: (state, userInfo) => {
state.userInfo = userInfo;
}
};
const actions = {
// 獲取密鑰
getKey({ commit }) {
return new Promise((resolve, reject) => {
getKey()
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
},
// 用戶登錄
login({ commit }, userInfo) {
// const { username, password } = userInfo;
const params = userInfo;
params.userName = userInfo.userName.trim()
return new Promise((resolve, reject) => {
// console.log(username, password);
// setToken(state.token)
// localStorage.setItem('loginToken', state.token)
getLogin(params)
// getLogin({ userName: username.trim(), password: password })
.then((response) => {
const { status, message, data } = response || {};
if (status === 200) {
// 存入 參數(shù): 1.調(diào)用的值 2.所要存入的數(shù)據(jù)
commit('SET_USER_INFO', data);
commit('SET_TOKEN', data.uuid);
commit('SET_USERID', data.id);
commit('SET_ROLES', data.roles);
commit('SET_NAME', data.realName);
commit('SET_TENANTID', data.tenantId || 1);
setToken(data.uuid);
db.save('userInfo', data);
db.save('tenantId', data.tenantId || 1);
localStorage.setItem('loginToken', data.uuid);
resolve(data);
} else {
// ElementUI.Message.error(message); // axios攔截統(tǒng)一提示了
}
})
.catch((error) => {
// ElementUI.Message.error(error.message); // axios攔截統(tǒng)一提示了
reject(error);
});
});
},
// 獲取用戶信息
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token)
.then((response) => {
const { data } = response;
data.roles = response.data.rights.map(String);
if (!data) {
reject('驗(yàn)證失敗,請(qǐng)重新登錄。');
}
const loginMessage = {
memberId: data.id,
userName: data.name,
userTel: data.mobile,
realName: data.realName,
incorCom: data.incorCom,
virtualCor: data.virtualCor,
deptId: data.deptId,
deptpath: data.deptpath,
deptName: data.deptName
};
localStorage.setItem('loginMessage', JSON.stringify(loginMessage));
const { id, roles, realName } = data;
// 角色必須是非空數(shù)組!
if (!roles || roles.length <= 0) {
reject('getInfo: 角色必須是非空數(shù)組!');
}
commit('SET_USERID', id);
commit('SET_ROLES', roles);
commit('SET_NAME', realName);
localStorage.setItem('userRights', roles);
// commit('SET_AVATAR', avatar)
// commit('SET_INTRODUCTION', introduction)
resolve(data);
})
.catch((error) => {
reject(error);
});
});
},
// 用戶登出
logout({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token)
.then(() => {
commit('SET_TOKEN', '');
commit('SET_ROLES', []);
db.remove('router');
removeToken();
resetRouter();
resolve();
})
.catch((error) => {
reject(error);
});
});
},
// 刪除token
resetToken({ commit }) {
return new Promise((resolve) => {
commit('SET_TOKEN', '');
commit('SET_ROLES', []);
removeToken();
resolve();
});
},
// 動(dòng)態(tài)修改權(quán)限
changeRoles({ commit, dispatch }, role) {
return new Promise(async(resolve) => {
const token = role + '-token';
commit('SET_TOKEN', token);
setToken(token);
const { roles } = await dispatch('getInfo');
console.log(roles, 'rolesrolesroles');
resetRouter();
// 根據(jù)角色生成可訪問(wèn)路由映射
const accessRoutes = await dispatch('permission/generateRoutes', roles, {
root: true
});
// 動(dòng)態(tài)添加可訪問(wèn)路由
router.addRoutes(accessRoutes);
// 重置已訪問(wèn)視圖和緩存視圖
dispatch('tagsView/delAllViews', null, { root: true });
resolve();
});
}
};
export default {
namespaced: true,
state,
mutations,
actions
};
這樣后可以按功能分module使用
頁(yè)面中調(diào)用就是
// 使用mutations
this.$store.commit('api/SET_T', keys);
// 使用actions
this.$store.dispatch('user/login', postUser).then(res => {
})
// 如果沒(méi)有分module
// 那就是 this.$store.commit('SET_T', keys);
// 直接調(diào)用方法
寫完自己也感覺(jué)好簡(jiǎn)單噢(⊙-⊙)
不明白的童鞋在評(píng)論區(qū)留言咯 ヾ(?ω?`)o