Karlom
Karlom

Reputation: 14834

How to include a component in all vue-routes?

In a SPA, I have made a header component which changes slightly on each page.

export default {
  name: 'header',
  //add some stuff based on user data
  data: function (router) {
    return {
      //some data      
    }
  },   
}

And here are my routes:

export default [
  {path:'/', component: showJokesAll },
  {path:'/hot', component: showJokesHotAll },
  {path:'/add', component: addJoke  }  ,
  {path: '/login', component: webLogin},
  {path: '/profile', component: webProfile},
  {path: '/auth', component: webProfile},

]

I'm wondering what is the correct way to inject the header component into all routes?

Update: When I try to import the header component into app's main.js:

import Header from './components/header.vue'

Vue.component('page-header', Header);

I get this error:

Failed to mount component: template or render function not defined.

Upvotes: 0

Views: 2716

Answers (1)

Georgi Antonov
Georgi Antonov

Reputation: 1641

If you want to have the same header component in all routes. place it before router-view and change your css layout. If you wan't to change the content of the header component depending on each route. You can place another <router-view name="header"> inside your header component. And then in your array of routes

 <template> 
        <div> 
          <app-header><../>
          <router-view><../>
        </div> 
    </template>

Otherwise:

export default [
  {
     path:'/', 
     components: {
       default: defaultComponentForThisRoute,
       header: yourRouteHeaderComponent,
     } 
  },


]

Upvotes: 2

Related Questions