Here, in this article, we will learn how to add a common header and footer component in our vuejs application.
Table of Contents
In general, we always have the same header and footer on all our pages on a website. And since vuejs is a component-based framework we don’t have to write HTML code for the header and footer on all our pages. We simply make two components: 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 components: 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 components 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
By local reference means we don’t have to import the component globally in the main.js file. Instead, we will import the components only on those pages where we need them locally.
Let’s see an example where we have called it only on one page.
<template>
<div id="app" class="page-container">
<header></header>
<div>
This is About Page.
</div>
<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.
Related Topics:
Update Parent Data From Child Component In VueJs
Include External CSS File In Vue.Js Component
How To Set Default Value Of Props In VueJS ?