做一个H5的项目时在项目中遇到场景需要使用路由守卫 beforeEach 路由守卫来对路由进行拦截,判断是直接进入页面或者需要先跳转到认证页面
router.beforeEach(async (to, from, next) => {
if (to.meta.isIntercept) {
let res = await checkOpenId(localStorage.getItem("openId"));
// console.log(res, "res");
if (res.data ? res.data.data : res) {
next();
} else {
next("/companyaccredited" + "?nextPath=" + to.fullPath);
}
} else {
next();
}
});
以上就是路由守卫的东西,在需要判断是否需要进入认证页面的路由中添加 meta 属性
{
path: "/complain",
name: "Complain",
meta: {
isIntercept: true,
},
component: () => import("@/pages/components/Complain/index.vue"),
},
isIntercept 为 true 代表需要进入认证页
当通过接口判断是否已经认证过,认证过则直接进入页面,未认证过则进入认证页面
代码运行之后遇到进入到对应的页面时,mounted() 生命周期中的代码不执行
通过排查,在每个对应的页面中加入 beforeRouteEnter
beforeRouteEnter(to, from, next) {
next((vm) => {
// 通过 `vm` 访问组件实例
vm.getCompany();
});
},
// getCompany 就是当时在 mounted() 生命周期中需要执行的代码
当在各个对应的页面中加入 beforeRouteEnter 时,问题解决