這篇文章主要介紹“VUEX狀態(tài)倉(cāng)庫(kù)管理的方法”,在日常操作中,相信很多人在VUEX狀態(tài)倉(cāng)庫(kù)管理的方法問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”VUEX狀態(tài)倉(cāng)庫(kù)管理的方法”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
創(chuàng)新互聯(lián)建站專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站制作、網(wǎng)站建設(shè)、甘孜州網(wǎng)絡(luò)推廣、小程序設(shè)計(jì)、甘孜州網(wǎng)絡(luò)營(yíng)銷、甘孜州企業(yè)策劃、甘孜州品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)建站為所有大學(xué)生創(chuàng)業(yè)者提供甘孜州建站搭建服務(wù),24小時(shí)服務(wù)熱線:028-86922220,官方網(wǎng)址:jinyejixie.com
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化。簡(jiǎn)單來說就是:應(yīng)用遇到多個(gè)組件共享狀態(tài)時(shí),使用vuex。
場(chǎng)景:多個(gè)組件共享數(shù)據(jù)或者是跨組件傳遞數(shù)據(jù)時(shí)
State:共享狀態(tài),vuex的基本數(shù)據(jù),用來存儲(chǔ)變量,相當(dāng)于組件data里的數(shù)據(jù),只不過此時(shí)變成了全局變量。
Getter:基于state的派生狀態(tài),相當(dāng)于組件中的computed中的屬性。
Mutation:更改vuex中store共享狀態(tài)的方法,通過提交mutation來去修改狀態(tài),進(jìn)行同步操作數(shù)據(jù),通常用于action獲取異步數(shù)據(jù),獲取通過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ù)丟失怎么解決?
先說一下為什么會(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中的變量。
vuex的安裝
打開終端,輸入命令行npm install vuex --save進(jìn)行下載vuex
這里新建store文件夾,創(chuàng)建一個(gè)js取名為index.js,
在index里 ,通過將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)})
我們通常將需要進(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用于更改state中的狀態(tài)邏輯的,且為同步更改state中的狀態(tài)數(shù)據(jù)。
需要知道的是在vuex中只能通過mutation來去修改state對(duì)象,
可以通過獲取actions獲取到的數(shù)據(jù)去修改state,也可以在mutations模塊中直接定義方法來去更改狀態(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; }};
通過mutations和下面的actions模塊,大家也可以看出commit是用于調(diào)用mutation模塊中的。
在組件中調(diào)用其mutation模塊的代碼為:
this.$store.commit('SET_TOKEN', token_data)
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 可以包含任意異步操作。
舉例
/* 下面就是通過actions執(zhí)行異步Ajax請(qǐng)求, 得到數(shù)據(jù)后, 通過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相當(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()
從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的方式
對(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ù)角色生成可訪問路由映射 const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true }); // 動(dòng)態(tài)添加可訪問路由 router.addRoutes(accessRoutes); // 重置已訪問視圖和緩存視圖 dispatch('tagsView/delAllViews', null, { root: true }); resolve(); }); }};export default { namespaced: true, state, mutations, actions};
這樣后可以按功能分module使用
頁(yè)面中調(diào)用就是
// 使用mutationsthis.$store.commit('api/SET_T', keys);// 使用actionsthis.$store.dispatch('user/login', postUser).then(res => {})// 如果沒有分module // 那就是 this.$store.commit('SET_T', keys);// 直接調(diào)用方法
到此,關(guān)于“VUEX狀態(tài)倉(cāng)庫(kù)管理的方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
標(biāo)題名稱:VUEX狀態(tài)倉(cāng)庫(kù)管理的方法
文章鏈接:http://jinyejixie.com/article8/gpsiip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、云服務(wù)器、搜索引擎優(yōu)化、網(wǎng)站制作、軟件開發(fā)、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)