Thursday, 17 June 2021

Vue how to change page title and favicon dynamically

favicon is the little icon displayed in browser tab

page title the title tag in header <header><title></title></head> is the description that will show up beside favicon in browser tab


by default, those two are located in VueProject/public/favicon.ico and VueProject/public/index.html

index.html contains <div id="app"></div> tag that Vue.JS compiled code will be injected there. Because in main.js there is new Vue({el:'#app' ....})


 https://stackoverflow.com/questions/59152176/how-to-change-page-favicon-title-with-vue-router


The page title can be dynamically changed in code by 

using :

 document.title = `APPLICATION_NAME - ${to.meta.title}`;
Or changed with route's meta tag info :

In addition to adding the 'meta' tag, you have to create a method that recieves the data inside this tag and apply the needed modifications.

  1. Add the 'meta' tag, like you just did above, but also add 'icon' property to it.

    {
     path: "/login",
     name: "Login",
     component: LoginComponent,
     meta: {
       title: "Login",
       icon:"/lock.png" 
     }
    }
    
  2. Go to your main *.vue file into which the various components will be routed through. This file is the one which has the element inside of it. In it, add a $route watcher in the scripts section of the file:

    watch: {
      $route(to) {
         document.title = `APPLICATION_NAME - ${to.meta.title}`;
         const link = document.querySelector("[rel='icon']")
         link.setAttribute('href',to.meta.icon)
      }
    }




No comments:

Post a Comment