gpt4 book ai didi

javascript - 如何在 vue-router beforeRouteEnter 钩子(Hook)中重定向到不同的 url?

转载 作者:可可西里 更新时间:2023-11-01 02:04:56 24 4
gpt4 key购买 nike

我正在使用 Vue.js 2 构建一个管理页面,我想阻止未经身份验证的用户访问 /admin 路由并将他们重定向到 /login。为此,我在 Admin 组件中使用了 In-Component Guard beforeRouteEnter,如下所示

...
beforeRouteEnter(to, from, next) {
if(userNotLogedIn) {
this.$router.push('/login');
}
}

这里的问题是 this 没有在 beforeRouteEnter 钩子(Hook)中定义。那么在这种情况下访问 $router 并重定向到不同 url 的正确方法是什么?

最佳答案

documentation指出:

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

您可以像这样调用 next 重定向到另一个页面:

beforeRouteEnter(to, from, next) {
if(userNotLogedIn) {
next('/login');
}
}

这是实现相同结果的另一种方法:因此,您可以使用 meta 属性在路由器配置中定义 protected 路由,而不是在每个 protected 路由上使用 beforeRouteEnter ,然后在所有路由上使用 beforeEach Hook 并检查 protected 路由并在需要时重定向到登录页面:

let router = new Router({    
mode: 'history',
routes: [
{
path: '/profile',
name: 'Profile',
component: Profile,
meta: {
auth: true // A protected route
},
},
{
path: '/login',
name: 'Login',
component: Login, // Unprotected route
},
]
})

/* Use this hook on all the routes that need to be protected
instead of beforeRouteEnter on each one explicitly */

router.beforeEach((to, from, next) => {
if (to.meta.auth && userNotLoggedIn) {
next('/login')
}
else {
next()
}
})

// Your Vue instance
new Vue({
el: '#app',
router,
// ...
})

关于javascript - 如何在 vue-router beforeRouteEnter 钩子(Hook)中重定向到不同的 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com