为什么路由器链接第一次不起作用?

时间:2020-05-13 06:13:58

标签: vue.js vuex vue-router quasar

我有一个grpc应用程序,有授权。启动项目时,您必须先登录。如果您尚未注册,我决定在登录按钮下添加。但是路由器不起作用。仅在入口处,进入注册页面。请帮助了解错误所在?为什么似乎被阻止了?

routes.js

  const routes = [
  {
    path: "/",
    component: () => import("layouts/MainLayout"),
    children: [
      {
        path: "",
        component: () => import("pages/Index"),
        meta: { requireAuth: true }
      },

      {
        path: "/logs",
        component: () => import("pages/Logs"),
        meta: { requireAuth: true, admin: true }
      }
    ]
  },
  {
    path: "/",
    component: () => import("layouts/AuthLayout"),
    children: [
      {
        path: "/welcome",
        component: () => import("pages/Auth"),
        meta: { guest: true }
      },
      {
        path: "/register",
        component: () => import("pages/Register"),
        meta: { guest: true }
      }
    ]
  }
];

我尝试了很多事情,例如在Auth.vue中:

  <q-item to='/register'>Sign Up</q-item> 
  <router-link tag="a" :to="{path:'/register'}" replace>Go</router-link>
  <span @click="callSomeFunc()">Register</span>
  ...
  methods: {
    callSomeFunc() {
    this.$router.push({ path: "/register" });
  }

我在App.vue中的路由器视图

for more information github repo

1 个答案:

答案 0 :(得分:0)

您的配置中有重复的路由-路径/用于2条路由。您应该解决此问题。

为防止未经授权的用户查看您的受保护页面,您可以通过beforeEach钩子向路由器添加全局导航保护:

import VueRouter from 'vue-router';

const routes = [
  {
    path: "/",
    component: () => import("layouts/MainLayout"),
    meta: { requireAuth: true },
    children: [
      {
        path: "",
        component: () => import("pages/Index"),
      },

      {
        path: "logs",
        component: () => import("pages/Logs"),
        meta: { admin: true }
      }
    ]
  },
  {
    path: "/login",
    component: () => import("layouts/AuthLayout"),
    children: [
      {
        path: "",
        component: () => import("pages/Auth"),
      },
      {
        path: "/register",
        component: () => import("pages/Register"),
      }
    ]
  }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) =>
{
  if (to.matched.some(route => route.meta.requireAuth))
  {
    if (userNotLogged) next('/login');
    else next();
  }
  else next();
});


export default router;

您还可以考虑阅读更详细的教程,例如https://www.digitalocean.com/community/tutorials/how-to-set-up-vue-js-authentication-and-route-handling-using-vue-router