How to add common header and footer in vuejs.


Here, in this article we will learn how to add a common header and footer component in our vuejs application.

In general we always have same header and footer in all our pages on a website. And since vuejs is a component based framework we don't have to write html code for header and footer in all our page. We simple make two component : header and a footer and then use in globally or locally on our web application.

There are two ways by which we can add header and footer in vuejs. By global reference and by local reference.

Method 1. By Global Reference

First create two component: header.vue and footer.vue.

And now in the main.js file.

import Vue from 'vue'
import App from './App.vue'
import header from './components/Header'
import footer from './components/Footer'

Vue.component('Header', header)
Vue.component('Footer', footer)

new Vue({
  router,
  render: h => h(App)
}).

And now these two component will be applied in all the routes in vuejs.

<template>
  <div id="app" class="main-container">
    <header></header>
    <router-view></router-view>
    <footer></footer>
  </div>
</template>

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

Method 2: By Local Reference

Here we don't have to import the component in main.js file. We will use it only where we need those component.

<template>
  <div id="app" class="main-container">
    <header></header>
    <router-view></router-view>
    <footer></footer>
  </div>
</template>

<script>
import header from './components/Header'
import footer from './components/Footer'

export default {
  name: 'about',
  components: {
    'header': header,
    'footer': footer
  }
}
</script>

Here we have imported both the header and footer component in our about page only.


💾 Recommended Articles