1

我刚刚将 vue-router 4 安装到 vue 3 应用程序中。在设置我的回家路线时,我不断让应用程序显示两次,甚至两次导航,但不知道为什么。我尝试将Navigation组件引入App.vueHome.vue但仍然显示两次。有什么东西是我在这里俯瞰的吗?

路由器/index.js

import { createWebHistory, createRouter } from "vue-router";
import Home from "../components/Home";
import About from "@/components/About";

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    {
        path: "/about",
        name: "About",
        component: About,
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;

导航.vue

<template>
  <div id="nav">
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
  </div>
  <router-view/>
</template>

<script>
export default {
  name: 'Navigation'
}
</script>

主页.vue

<template>
    <Header/>
    <Navigation/>
    <div>
        <About/>
    </div>
</template>

应用程序.vue

<template>
  <Home/>
</template>

<script>
import Home from "@/components/Home";
export default {
  components: {Home}
}
</script>
4

1 回答 1

2

Home包含Navigation(其中包含<router-view>,呈现当前路线) About. 由于About总是渲染,如果当前路线是/about.

<template>
  <Header/>
  <Navigation/> <!-- contains router-view -->
  <div>
    <About/> <!-- ❌ always rendered in addition to current route -->
  </div>
</template>

你当前的路由配置没有子路由,所以应该只有一个<router-view>,并且通常在根组件(App.vue)中:

应用程序.vue:

<template>
  <Header />
  <Navigation />
  <router-view />
</template>

导航.vue:

<template>
  <div id="nav">
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
  </div>
  <!--<router-view/> ❌ move to App.vue -->
</template>

主页.vue:

<template>
  <!--<Header/> ​❌ move to App.vue -->
  <!--<Navigation/> ❌ move to App.vue -->
  <div>
    <About />
  </div>
</template>

演示

于 2021-07-20T20:35:45.700 回答