由于uni-app没有vue中的全局钩子函数,所以封装了Router对象
- 首先我们创建一个JS文件,用于存放路由跳转的方法(文件路径src/utils/router.js)
class Router {
constructor() {
this.callBack = () => {};
}
beforeEach(callBack) {
if (callBack instanceof Function) this.callBack = callBack;
}
push(to) {
this.callBack('navigateTo', to);
}
redirectTo(to) {
this.callBack('redirectTo', to);
}
reLaunch(to) {
this.callBack('reLaunch', to);
}
switchTab(to) {
this.callBack('switchTab', to);
}
back(delta) {
history.back();
uni.navigateBack({
delta
});
}
}
export default new Router();
import $mRouter from '@/utils/router';
Vue.prototype.$mRouter = $mRouter;
- 路由拦截操作,调用Router对象中的beforeEach方法(文件路径src/main.js)
$mRouter.beforeEach((navType, to) => {
if (to.route === undefined) {
throw '路由钩子函数中没有找到to对象,路由信息:' + JSON.stringify(to);
}
if (to.route === $mRoutesConfig.login.path && store.getters.hasLogin) {
uni.reLaunch({
url: $mHelper.objParseUrlAndParam($mRoutesConfig.main.path)
});
return;
}
if (to.route.requiresAuth) {
if (store.getters.hasLogin) {
uni[navType]({
url: $mHelper.objParseUrlAndParam(to.route.path, to.query)
});
} else {
const query = {
redirectUrl: to.route.path,
...to.query
};
uni.navigateTo({
url: $mHelper.objParseUrlAndParam($mRoutesConfig.login.path, query)
});
}
} else {
uni[navType]({
url: $mHelper.objParseUrlAndParam(to.route, to.query)
});
}
});
this.$mRouter.reLaunch({ route: '/pages/profile/profile' })
- 想知道uni-app如何封装request请求,请看这里