在导航守卫运行之前安装App.vue

问题描述 投票:0回答:1

这有点牵强,因为我必须粘贴大量代码来显示我的项目设置。我注意到我的

App.vue
文件在路线文件的导航防护之前加载。这导致了一系列奇怪的问题。导航守卫应该覆盖整个 Vue 应用程序,还是只是路线?这正常吗?

注意之后的日志

router.beforeEach()

此记录在

App.vue
之后..显然不应该...

我的

main.ts
文件:

import App from '@/views/App.vue'
import store from "./store"
import createRouter from './router'

const router = createRouter(store)
const UI = createApp(App)

UI.use(store)
UI.use(router)

UI.mount('#app')

我的

route.ts
文件:

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    meta: {
      auth: true
    }
  },

];

export default function (store: any) {
  const router = createRouter({
    routes,
    history: createWebHistory(),
    scrollBehavior(to, from, savedPosition) {
      return { top: 0 }
    }
  })

  router.beforeEach(async (to, from, next) => {
    console.log('beforeEach')
    store.commit(`auth/setUseAuth`, to.meta.auth)

    if (to.query.state != null && to.query.state !== "") {
      ...redacted
    } else {
      ...redacted
    }

    // If the route needs authentication
    if (to.meta.auth) {

      // If we have a stored token, proceed
      if (hasToken()) {
        next()
        return
      }

      // If we DO NOT have a stored token

      if  ( // But we have a non-empty query code...
            (to.query.code && to.query.code !== "") ||
            // Or a non-empty JWT passed in...
            (to.query.jwt && to.query.jwt !== ""))
      {
        store.dispatch({
          type: 'auth/validateCode',
          payload: {
            ...redacted payload
          }
        });

        next()
        return
      }
    }
    // For all other requests, move forward
    next()
  })

  return router
}

vue.js vuejs3 vue-router
1个回答
0
投票

导航守卫只是覆盖路线。

我不清楚导航守卫在做什么,因为所有路径都以

next()
结尾。 (请注意,
next
不再推荐。)如果您想在需要时重定向到登录页面,您的导航防护应该执行以下操作:

router.beforeEach((to) => {
  if (to.meta.auth && !hasToken()) {
    return '/login';
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.