在导航卫士运行之前安装app.vue

bprjcwpo  于 7个月前  发布在  Vue.js
关注(0)|答案(1)|浏览(73)

这有点牵强,因为我必须粘贴相当多的代码来显示我的项目设置。我注意到我的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
}

mbzjlibv

mbzjlibv1#

导航警卫只负责航线。
我不清楚导航守卫在做什么,因为所有路径都以next()结束。(注意,next不再被推荐。)如果你想在需要时重定向到登录页面,你的导航守卫应该做如下事情:

router.beforeEach((to) => {
  if (to.meta.auth && !hasToken()) {
    return '/login';
  }
});

字符串

相关问题