【问题标题】:Vue-Router beforeEnter not function as expected?Vue-Router beforeEnter 没有按预期运行?
【发布时间】: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


【解决方案1】:

试试:

- beforeEnter: authGaurd
+ beforeEnter(to, from, next) {
    authGaurd(to, from, next)
  }

【讨论】:

  • 我最终改变了.. export const authGaurd to.. const authGaurd 并将 export default authGaurd 添加到文件底部,它似乎可以工作。
  • 你的答案是正确的,你能提供更多关于它为什么有效的细节吗?
猜你喜欢
  • 2016-12-17
  • 2015-05-26
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
相关资源
最近更新 更多