by Sai gowtham

How to change the favicon dynamically in Vue

In this tutorial, we are going to learn about how to dynamically change the favicon in a Vue app.

Note: This tutorial, assumes that you already created a new vue project using vue cli.

Changing the favicon dynamically

  1. Open the Vue project in your favorite code editor.
  2. Navigate to the public folder and open the index.html file, add the id attribute to the following link tag.
<link rel="icon" id="favicon" href="<%= BASE_URL %>favicon.ico">

Now, we can access this favicon link tag inside our App.vue file by using the document.getElementById() method then we need to update its href property with a new favicon like this.

App.vue
<template>
  <div id="app">
    <button @click="handleIcon()">Change icon</button>  </div>
</template>

<script>
export default {
  methods: {
    handleIcon() {
                       // accessing the link tag
      const favicon = document.getElementById("favicon");      favicon.href = "https://www.google.com/favicon.ico";    }
  }
};
</script>

If we click on the Change icon button, the handleIcon() method is invoked and the current favicon is changed to Google's favicon.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course