简体   繁体   中英

Vue <router-view/> loads header components twice

I am building a simple vue app and I encountered a strange issue where the components in my tag are rendered a second time inside the tag.

Originally, the and components were not in a header tag but they appeared below the component.

App.vue

<template>
  <div id="app">
    <header><app-logo/><nav-bar/></header>
    <section class="container">
    <router-view/>
    </section>
  </div>
</template>
<script>
import AppLogo from './components/AppLogo.vue'
import Home from './components/Home.vue'
export default {
  name: 'App',
  components: {
    Home,
    AppLogo
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.title {
  font-family: "Quicksand", "Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; /* 1 */
  display: block;
  font-weight: 300;
  font-size: 100px;
  color: #35495e;
  letter-spacing: 1px;
}
.subtitle {
  font-weight: 300;
  font-size: 42px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}
.links {
  padding-top: 15px;
}
</style>

nav-bar component:

<template>
    <div>
        <h1> TFJS/Vue Examples </h1>
        <div v-for="page in pages" v-bind:key="page">
            <div>
                <div>
                    <router-link to='/basic-logistic-regression'> {{ page }} </router-link>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            pages: ['/BasicLogisticRegression']
        }
    }
}
</script>

I want to have nav-bar component appear above the router view at all times.

I solved this problem by using a mounted method called loadHome() which uses this.$router.push('/home') to programatically force the router-view to load the homepage component.

here is the code

App.vue

<template>
  <div id="app">
    <div class="routing">
      <header><app-logo/><nav-bar/></header>
    </div>
    <section class="container">
    <router-view/>
    </section>
  </div>
</template>

<script>
import AppLogo from './components/AppLogo.vue'
import NavBar from './components/NavBar.vue'
import Home from './components/Home.vue'

export default {
  name: 'App',
  components: {
    Home,
    AppLogo,
    NavBar
  },
  methods: {
    loadHome: function(){
      this.$router.push('/home')
    }
  },
  mounted: function(){
    this.loadHome()
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM