【问题标题】:Error: Redirected when going from "/" to "/dashboard" via a navigation guard错误:通过导航守卫从“/”转到“/dashboard”时重定向
【发布时间】:2020-08-11 20:53:06
【问题描述】:

出于某种我不明白的原因,Vue 引发了以下错误:Error: Redirected when going from "/" to "/dashboard" via a navigation guard.

我知道这发生在哪里:

import { Component, Vue } from "vue-property-decorator";
import { Route } from "vue-router";

@Component({
  async beforeRouteEnter(to, from, next) {
    const sites = getUserSite();

    if (sites && sites.length) {
      next();
    } else {
      next("/sites/create");
    }
  }
})
export default class Dashboard extends Vue {}

我不想让用户访问 /dashboard,除非他们在数据库中至少有一个站点。我不知道为什么会这样。谁能给我一盏灯?

【问题讨论】:

  • 您好,对我来说您的代码看起来不错。我曾经遇到过类似的问题。我通过删除 node_modules 和 package-lock.json 并运行 npm install 来修复它。也许有帮助。
  • 可以分享getUserSite()功能码吗?

标签: vue.js vue-router


【解决方案1】:

我同意 Christoph Dietrich 的评论:您的代码似乎没问题。唯一的区别是我用来配置navigation guard 的地方。我在我的 main.js 文件中配置了它,在同一个地方配置所有导入和 Vue 实例本身:

//Import the Vue Router in order to use it
import VueRouter from "vue-router";

//In my case, I import the configuration for each route for aesthetic reasons (it's a huge file)
import Routes from "./utils/routes.js";

//Configure Vue to use the Router
Vue.use(VueRouter);

//Instantiate/Configure the router
const router = new VueRouter({
    routes: Routes,
    mode: "hash",
});

//Configure the navigation guard
router.beforeEach((to, from, next) => {
    //Note that I'm using a global "beforeEach" navigation guard, 
    //therefore, I have to check if I am coming from the "/" page
    //and I want to go to the "/dashboard:

    if (from.path == "/" && to.path == "/dashboard") {
        const sites = getUserSite();

        if (sites && sites.length) {
            next();
        } else {
            next("/sites/create");
        }
    }
    
});

function getUserSite() {
    ....
}

//Mount the Vue instance with the router:
new Vue({
    render: (h) => h(App),
    router: router,
}).$mount("#app");
  • 您可以使用Named 路由或meta fields 来验证路由是否需要任何验证,而不是from.path == "/" && to.path == "/dashboard"

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2020-11-23
    • 2021-02-03
    • 1970-01-01
    相关资源
    最近更新 更多