首页 > 解决方案 > Vue 路由器无法从嵌套视图嵌套子级访问根应用程序路径“/”

问题描述

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

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 或手动this.$router.push({name: 'Home'})this.$router.push({name: '/'})从 /account/avatars 例如单击 router-link 或 $router.push 根本不起作用。

应用程序.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.jsvuejs2vue-router

解决方案


检查里面有什么BASE_URL。构造函数的.base参数VueRouter不是您应用的 baseUrl。这只是默认路径。Vue 路由器官方文档。它应该是base:'/'

检查这个工作代码:

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

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

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

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


推荐阅读