SahnaS
SahnaS

Reputation: 89

Dynamically binding title tag in vuejs

I'm new to vuejs.

I try to bind data on the title tag dynamically. I used vue-head to do this on a simple html page. I do not use webpack and npm.

This is how I bind the title tag :

var app = new Vue({
            el: 'html',
            head: {
              title: function () {
                return {
                    inner: this.remaining + ' Tâches',
                    separator: ' ',
                    complement: ' '   
                }
              }
            }

In the vue-head documentation, they suggest to do this :

methods: {
  getAsyncData: function () {
    var self = this
    window.setTimeout(function () {
    self.title = 'My async title'
    self.$emit('updateHead')
    }, 3000)
  }
},

I also tried to set it in the watch prop, but it didn't work.

Here is my entire code : https://jsfiddle.net/5d70s0s6/1/

Thanks

Upvotes: 3

Views: 4684

Answers (1)

Ikbel
Ikbel

Reputation: 7851

Use a computed property.

computed: {
  title: {
    get() {
      document.title = this.remaining
      return this.remaining
    },
    set(val) {
      document.title = val
    }
  }
}

You don't need to use <title>{{title}}</title>. If you change title in your Vue, it will be applied automatically to the page.

Also, you should not bind a Vue instance to html, head or body tags. Use regular elements only like <div id="app"></div> and set your Vue el: '#app'

Or you could use this:

data: {
  title: '',
},
watch: {
  title(val) {
    document.title = val
  }
}

Update: While the code above can solve your problem. I created this tiny vue-title component that can be used in your project easily.

Example:

<vue-title>{{title}}</vue-title>

Upvotes: 4

Related Questions