【问题标题】:Vue router cannot access root app path '/' from nested view nested childrenVue 路由器无法从嵌套视图嵌套子级访问根应用程序路径“/”
【发布时间】:2021-08-12 05:20:38
【问题描述】:

我正在尝试从具有嵌套子项的嵌套视图访问应用程序“/”或命名组件“Home”的根路径。

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    ...
    {
        path: "/account",
        name: "Account",
        component: AccountHome,
        children: [
            {
                name: "AccountAvatars",
                path: "avatars",
                component: AccountAvatar,
            },
         ...
        ],
    },
];

const router = new VueRouter({
    mode: "history",
    base: '/',
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { x: 0, y: 0 };
    },
});

Vue.use(VueRouter);

export default router;
    ....

当我想使用 router-link 或手动使用 /account/avatars 中的 this.$router.push({name: 'Home'})this.$router.push({name: '/'}) 时,例如单击 router-link 或 $router.push 根本不起作用。

App.vue

<template>
    <div id="app">
        <global-header />
        <router-view />
        <global-footer />
    </div>
</template>

首页.vue

<template>
    <div class="home">    
        <offer />
        <home-menu />
        <game-catalog/>
        <benefits />
        <news />
    </div>
</template>

AccountHome.vue

<template>
    <div class="container">
        <div
            class="account"
        >
            <account-left-sidebar />
            <router-view />
            <account-right-sidebar />
        </div>
    </div>
</template>

路由器实例

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

【问题讨论】:

标签: vue.js vuejs2 vue-router


【解决方案1】:

检查 BASE_URL 里面的内容。 VueRouter 构造函数的 .base 参数不是您应用的 baseUrl。这只是默认路径。 official Vue Router doc。应该是base:'/'

检查此工作代码:

https://codesandbox.io/s/holy-bush-jsi79?file=/src/routes.js

编辑:我也添加了编程路由示例。(以匹配您的编辑)

编辑 2:我还添加了另一个与您的编辑完全相同的运行示例。它仍然有效。我认为您的组件之一正在摆弄路由器。

https://codepen.io/rabelais88/pen/NWjJEMe

【讨论】:

  • 我已经试过了(base: '/'),它不起作用:(
  • 再次检查示例。我还添加了与您的完全相同的路由,它仍然有效。如果它在你的代码中仍然不起作用,我认为我们在你的写作中遗漏了一些东西。请给我们一个可重现的例子。
  • 我还添加了另一个与您的编辑完全相同的示例。我认为您的示例缺少解决问题的关键部分。请在下次发布到 stackoverflow 之前创建一个可重现的环境。我知道这样做会让您感到沮丧,但这样可以节省更多时间。
猜你喜欢
  • 2017-10-02
  • 2019-01-06
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
相关资源
最近更新 更多