在 Vue 3 中,beforeRouteEnter 是一个导航守卫,用于在路由进入之前执行一些逻辑。它不能直接访问 this,因为当守卫执行时,组件实例还没有被创建。你需要通过传入一个回调函数来访问组件实例。
以下是包含解释的示例代码:
<template>
<div>
<p>This is a protected page</p>
</div>
</template>
<script>
export default {
name: 'ProtectedPage',
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不能获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
// 检查用户是否已登录
const isAuthenticated = /* some logic to check if user is authenticated */ true;
if (isAuthenticated) {
next(); // 继续路由
} else {
next('/login'); // 重定向到登录页面
}
},
mounted() {
console.log('Component has been mounted');
}
};
</script>
如果你需要访问组件实例,可以在 next 回调中传递它:
beforeRouteEnter(to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
console.log(vm);
});
}
上一篇:vue md5
下一篇:vue watch深度监听
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站