【发布时间】:2019-11-01 06:31:20
【问题描述】:
我正在尝试使用 beforeEnter 保护路线。我的路线看起来像这样;
path: '/account',
name: 'account',
component: Account,
beforeEnter:
(to, from, next) => {
const authService = getInstance();
const fn = () => {
// If the user is authenticated, continue
if (authService.isAuthenticated) {
console.log('no')
return next();
}
// Otherwise, log in
console.log('should login')
authService.loginWithRedirect({ appState: { targetUrl: to.fullPath } });
};
if (!authService.loading) {
return fn();
}
authService.$watch("loading", loading => {
if (loading === false) {
return fn();
}
})
}
},
这个功能如我所料,但我不相信逻辑应该在路由文件中,所以我将它存储在我的 auth 文件夹下的另一个文件中。像这样;
import { getInstance } from "./index";
export const authGuard = (to, from, next) => {
console.log('test')
const authService = getInstance();
const fn = () => {
// If the user is authenticated, continue with the route
if (authService.isAuthenticated) {
console.log('no')
return next();
}
// Otherwise, log in
console.log('should login')
authService.loginWithRedirect({ appState: { targetUrl: to.fullPath } });
};
// If loading has already finished, check our auth state using `fn()`
if (!authService.loading) {
return fn();
}
// Watch for the loading property to change before we check isAuthenticated
authService.$watch("loading", loading => {
if (loading === false) {
return fn();
}
});
};
但是,当我将其导入我的路线并执行时;
import { authGaurd } from './auth/authGaurd'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/account',
name: 'account',
component: Account,
beforeEnter: authGaurd
},
这不再有效?我确定我一定遗漏了一些简单的东西?任何帮助将不胜感激。
【问题讨论】:
-
你有什么错误吗?你的 authGaurd 被调用了吗?
-
我不确定问题是什么,但使用
Vue.use(Router)然后使用export default new Router(..)导出实际路由器对我来说看起来有点奇怪......您是否在其他地方使用导出的路由器对象?
标签: vue.js vue-router auth0