Modifying the document title dynamically with Vue.js

Published on 2020-05-16 • Modified on 2020-05-16

In this snippet we will see how to alter the title element of an HTML document dynamically. It is something I use on my pomodoro.fun project where the title is updated every seconds with the time left of the countdown. In this snippet, we update the title with a random number every seconds.


/**
 * I am using a JavaScript module to isolate the code of each snippet.
 * In fact it's a Vue.js mixin. Take the code called by the mounted()
 * or the snippetXX() function.
 */
export default {
  data: {
    title: 'Strangebuzz'
  },
  methods: {
    snippet91 () {
      const self = this
      setInterval(function () {
        self.title = Math.random() + ' | ' + self.trans.snippet_91_title
      }, 1000)
    }
  },
  watch: {
    title: {
      immediate: true,
      handler () {
        document.title = this.title
      }
    }
  },
  mounted () {
    if (this.isArticle(91)) {
      this.snippet91()
    }
  }
}

 More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!