useGlobalState.js
const STORAGE_PREFIX = 'USE_GLOBAL_STATE_';
const storageData = {};
/**
* 对state进行格式化
* @param {*} storage
*/
function initStorageData(storage) {
const { keys = [] } = storage || {};
const now = new Date().getTime();
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (key.indexOf(STORAGE_PREFIX) === 0) {
let result = my.getStorageSync({ key }) || {};
let value = result.data;
try {
value = JSON.parse(value);
if (!value.timeout || now - value.time < value.timeout) {
let storageKey = key.substring(STORAGE_PREFIX.length);
storageData[storageKey] = value.state;
} else {
my.removeStorageSync({
key
});
}
} catch (e) { }
}
}
}
//初始化一次
initStorageData(my.getStorageInfoSync());
//设置缓存位置,及过期时间
const defaultOptions = {
storage: null, //local
storageTimeout: 0
};
//获取全局数据
function getGlobalState(name) {
return storageData[name];
}
function setGlobalState(name, state, options = {}) {
storageData[name] = state;
if (options.storage === 'local') {
my.setStorageSync({
key: STORAGE_PREFIX + name,
data: JSON.stringify({
state,
timeout: options.storageTimeout,
time: new Date().getTime(),
})
});
}
}
export default (defaultState, key, options) => {
if (typeof key === 'undefined' && typeof options === 'undefined') {
key = defaultState;
defaultState = undefined;
} else if (typeof key === 'object' && typeof options === 'undefined') {
options = key;
key = defaultState;
defaultState = undefined;
}
options = {
...defaultOptions,
...options,
};
const getState = () => {
return getGlobalState(key);
}
// let state = getState();
const setState = (newState) => {
setGlobalState(key, newState, options);
// state = newState;
};
return [getState, setState];
};
hijackPage.js
import useGlobalState from "./useGlobalState";
const [getAuthUser, setAuthUser] = useGlobalState("USER", { storage: "local" });
const defaultConfig = {
auth: false //是否需要验证用户登录状态及权限
}
/**
* 验证用户登录信息,也可以在这里刷新权限,重新获取token
*/
const authVerify = () => {
const authUser = getAuthUser();
// authUser && console.log("用户信息", authUser);
if (!authUser) {
my.navigateTo({ url: '/pages/auth/login/index' })
}
}
export default function (options = {}, pageConfig = {}) {
//页面配置
const config = {
...defaultConfig,
...pageConfig
}
//对onLoad进行重写
var _onLoad = options.onLoad;
options.onLoad = function (opt = {}) {
//验证用户登录状态
config.auth && authVerify();
//增加一个页面周期
options.beforeLoad && options.beforeLoad(opt);
//执行页面onLoad,利用apply()挂载到页面this,并接受数组中的参数
_onLoad && _onLoad.apply(this, [opt]);
}
//将经常用的一些方法挂在到page
options.setAuthUser = setAuthUser;
options.getAuthUser = getAuthUser;
//开始执行页面
Page(options);
}
页面使用实例
import hijackPage from "../../hooks/hijackPage";
hijackPage({
data() {
return {
userInfo: this.getAuthUser()
}
},
beforeLoad(query) {
//只执行一次,并且不能对data进行修改
},
onLoad(query) {
console.log("home-userInfo", this.data.userInfo);
console.log("home-query", query);
this.getVCarList();
},
onReady() {
// 页面加载完成
},
onShow() {
// 页面显示
},
onHide() {
// 页面隐藏
},
onUnload() {
// 页面被关闭
},
onTitleClick() {
// 标题被点击
},
onPullDownRefresh() {
// 页面被下拉
},
onReachBottom() {
// 页面被拉到底部
},
onShareAppMessage() {
// 返回自定义分享信息
return {
title: 'My App',
desc: 'My App description',
path: 'pages/index/index',
};
},
getVCarList() {
console.log("获取车辆列表");
}
}, { auth: true });