user3147268
user3147268

Reputation: 1884

Vuejs: shared components used on multiple pages disappeared

right now, I'm writing a single-page-application in vue.js using vue-router. Pages like the homepage, sign-in page etc. all share a navigation and footer component. On a few pages however, I need the entire screen so that the navigation and footer shall not be displayed.

Hence, I decided to nest components and include the navigation and footer component when necessary. My problems now is, that the navigation and footer template disappeared on all pages.

Edit: A more complete demo can be found in this Github repository.

Here's a simplified version of the files I'm using:

index.html:

<div id="app">
  <router-view></routerview> 
</div>

router.js:

import Homepage from './homepage.vue';
import SignIn from './signin.vue';

const router = new VueRouter({
  routes: [
    {path: '/', component: Homepage},
    {path: '/signin', component: SignIn},
    ]
})

homepage.vue and signin.vue components:

<template>
  <navigation></navigation>  
    // some page-specific content
  <footer-vue></footer-vue>
</template>

<script>
import Navigation from './navigation.vue';
import Footer from './footer.vue';

export default {
  components: {
      'navigation': Navigation,
      'footer-vue': Footer,
  },
}
</script>

A component without navigation and footer:

<template> 
// some page-specific content
</template>

Is it even possible to nest components this way? I hope someone is able to point me into the right direction.

Upvotes: 0

Views: 1470

Answers (1)

skirtle
skirtle

Reputation: 29092

Both homepage.vue and signin.vue have invalid templates. e.g.

<template>
    <navigation></navigation>
    <h1>The homepage</h1>
    <footer-vue></footer-vue>
</template>

This is not allowed as it has 3 root nodes. See https://v2.vuejs.org/v2/guide/components.html#A-Single-Root-Element

You need to wrap it to get it to work:

<template>
    <div>
        <navigation></navigation>
        <h1>The homepage</h1>
        <footer-vue></footer-vue>
    </div>
</template>

Note that this limitation does not apply to functional components and is also expected to be lifted for all components in Vue 3.

Much more worrying is that you're not seeing any errors messages for this. You really need to look into that as it suggests there's something very much amiss with your development setup.

An example of the error message you should be seeing:

new Vue({
  el: '#app',
  template: '<div></div><div></div>'
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
</div>

Upvotes: 2

Related Questions