Vue-Router beforeEnter не работает должным образом? - PullRequest
0 голосов
/ 31 октября 2019

Я пытаюсь защитить маршрут, используя 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
        },

, это больше не работает? Я уверен, что я должен пропустить что-то простое? Любая помощь будет высоко ценится.

1 Ответ

1 голос
/ 01 ноября 2019

Попробуйте:

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