一種常見的需求是,當(dāng)處于某種狀態(tài)(如登錄狀態(tài)),或進(jìn)行了設(shè)置(如地區(qū)選擇),在瀏覽器刷新后如何恢復(fù)設(shè)置和狀態(tài)。
localStorage保存設(shè)置
我一般用localStorage保存重要的設(shè)置,而不用來(lái)保存狀態(tài)。因?yàn)闋顟B(tài)特別關(guān)鍵需要服務(wù)器確認(rèn)。用一點(diǎn)流量還是值得的。
localStorage的setter和getter都應(yīng)當(dāng)放到store中處理,然后根據(jù)此設(shè)置是全局設(shè)置還是局部設(shè)置,在相應(yīng)的.vue文件mounted方法中dispatch。如下,注意actions-init和actions-initForLogin
store/area.js
import { getAreaName, setArea } from "@/api/api.js"
import { getLocalStorageArray, getLocalStorageObject, setLocalStorageItem } from '@/tool/localStorage.js'
export default {
namespaced: true,
state: function () {
return {
cascaderOptions: [],
currentArea: [/*shengValue,shiValue,xianValue,zhenValue */],
zhenName: "",/* value: name*/
}
},
mutations: {
setCurrentArea: function (state, payload) {
state.currentArea = payload.currentArea
const JSONCurrentArea = JSON.stringify(payload.currentArea)
setLocalStorageItem('areaCurrentArea', JSONCurrentArea)
},
setName: function (state, payload) {
state.zhenName = payload.name
},
getLSOptions: function (state) {
state.options = JSON.parse(getLocalStorageObject('areaOptions'))
},
getLSCurrentArea: function (state) {
state.currentArea = JSON.parse(getLocalStorageArray('areaCurrentArea'))
},
},
actions: {
setName: async function ({ state, commit }) {
if (state.currentArea && state.currentArea[3]) {
const obj = await getAreaName(state.currentArea[3])
commit('setName', { name: obj.name })
}
},
init: async function ({ commit }) {
commit('getLSOptions')
commit('getLSCurrentArea')
},
initForLogin: async function ({ commit, dispatch, state }) {
commit('getLSOptions')
commit('getLSCurrentArea')
await setArea(state.currentArea[3]);
dispatch('setName')
dispatch('getNews', null, { root: true })
dispatch('getInfos', null, { root: true })
}
}
}
然后在需要的此獲取該緩存的地方dispatch,下面都是局部.vue調(diào)用,后面會(huì)給出全局條用的例子
login.vue
mounted: function() {
this.__init();
window.onresize = this.resize;
},
destroyed() {
window.onresize = null;
},
methods: {
__init: async function() {
this.$store.dispatch("area/initForLogin");
this.resize();
this.getVerifyPictureSrc();
},
resize: debounce(function() {
this.height = scaleHeightWithWindow(0.75);
}, 100),
getVerifyPictureSrc: async function() {
await deleteVerifyPicture();
this.verifyPictureSrc = "/api/verifypic?force=" + Math.random();
},
userLogin: function() {
this.$store.dispatch("user/login", {
callback: this.getVerifyPictureSrc
});
// this.getVerifyPictureSrc();
},
logout: function() {
this.$store.dispatch("user/logout", { router: this.$router });
}
},
poster.vue
mounted() {
this.___init();
this.handlerResize();
window.onresize = debounce(this.handlerResize, 300);
this.throttleHandleScroll = throttle(this.handleScroll, 600);
window.addEventListener("mousewheel", this.throttleHandleScroll);
window.addEventListener("DOMMouseScroll", this.throttleHandleScroll);
},
destroyed() {
window.onresize = null;
window.removeEventListener("mousewheel", this.throttleHandleScroll);
window.removeEventListener("DOMMouseScroll", this.throttleHandleScroll);
},
methods: {
handleScroll: function(e) {
if ((e.detail || e.deltaY) > 0) this.$refs.carousel.next();
else this.$refs.carousel.prev();
},
handlerResize: function() {
this.height = window.innerHeight + "px";
},
___init: async function() {
await this.$store.dispatch("area/init");
}
}
從后臺(tái)請(qǐng)求狀態(tài)
注意actions-init
store/user.js
/**
* 用戶登錄
*/
import { userLogin, getLoginInfo, logout } from '@/api/api.js'
import Vue from 'vue'
export default {
namespaced: true,
state: function () {
return {
loginInfo: {
name: '',
pass: '',
verify: '',
type: 1, /*1是政府賬戶 2是企業(yè)賬戶 */
},
loginStatus: -4/**0-成功 -1 -2 -3 -4 */
}
},
mutations:
{
setName: function ({ loginInfo }, { name }) {
loginInfo.name = name
},
setPass: function ({ loginInfo }, { pass }) {
loginInfo.name = pass
},
setVerify: function ({ loginInfo }, { verify }) {
loginInfo.verify = verify
},
setType: function ({ loginInfo }, { type }) {
loginInfo.verify = type
},
setStatus: function (state, { status }) {
state.loginStatus = status
},
reset: function (state) {
state.loginStatus = -4;
const { loginInfo } = state;
loginInfo.name = '';
loginInfo.pass = '';
loginInfo.verify = '';
}
},
actions: {
login: async function ({ state, commit }, { callback }) {
const res = await userLogin(state.loginInfo)
const v = res.code
commit('setStatus', { status: v })
if (v == 0) {
Vue.prototype.$message({
type: "success",
message: "登錄成功"
});
} else {
let msg =
v == -1 ? "驗(yàn)證碼錯(cuò)誤" : v == -2 ? "用戶名或密碼錯(cuò)誤" : "用戶不存在";
Vue.prototype.$message({
type: "error",
message: msg
});
}
callback()
},
logout: async function ({ commit }, { router }) {
await logout()
commit('reset')
router.push('login')
},
init: async function ({ commit }) {
const loginInfo = await getLoginInfo()
const { loginName, loginType/**cityId,provinceId */ } = loginInfo
commit('setName', { name: loginName })
commit('setStatus', { status: (loginType == 1 ? 0 : -1) })
}
}
}
這個(gè)狀態(tài)屬于全局狀態(tài),每次刷新站都要請(qǐng)求
app.vue
mounted() {
this.$store.dispatch("user/init");
}
謝謝