How to add common header and footer in vuejs.
In this article we will learn how to import a common header and footer component in our vuejs application. We can do it by global reference and local reference.
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 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 ?
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
