错误:通过导航卫士从“ /”转到“ / dashboard”时重定向

时间:2020-08-11 20:53:06

标签: vue.js vue-router

出于某种我不了解的原因,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。我不知道为什么会这样。有人可以给我个灯吗?

1 个答案:

答案 0 :(得分:0)

我同意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"来验证路由是否需要任何验证。