【问题标题】:Vue router 4 and vue 3 app showing component twiceVue 路由器 4 和 Vue 3 应用程序两次显示组件
【发布时间】:2021-09-26 15:28:32
【问题描述】:

我刚刚将 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>

App.vue

<template>
  <Home/>
</template>

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

【问题讨论】:

    标签: javascript vue.js vuejs3 vue-router4


    【解决方案1】:

    Home 包含Navigation(其中包含&lt;router-view&gt;,渲染当前路线) About。因为About 总是被渲染,如果当前路由是/about,你会看到其中两个。

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

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

    App.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>
    

    Home.vue:

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

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-08
      • 2018-12-27
      • 2021-12-29
      • 2021-06-29
      • 2018-12-12
      • 2019-07-23
      • 1970-01-01
      • 2020-05-11
      相关资源
      最近更新 更多