How to inject elements into the head element with Vue.js and JavaScript?

Sometimes, we want to inject elements into the head element with Vue.js and JavaScript.

In this article, we’ll look at how to inject elements into the head element with Vue.js and JavaScript.

How to inject elements into the head element with Vue.js and JavaScript?

To inject elements into the head element with Vue.js and JavaScript, we can use the vue-head library.

To use it, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.rawgit.com/ktquez/vue-head/master/vue-head.js"></script>


<div id='app'>

</div>

to add the Vue and vue-head scripts with the app container element.

Then we write:

const v = new Vue({
  el: '#app',
  template: '<p>hello</p>',
  data: {
    title: 'My Title'
  },
  head: {
    title() {
      return {
        inner: this.title
      }
    },
    meta: [{
      name: 'description',
      content: 'My description'
    }]
  }
})

to add the head property which is set to an object with the title method which returns the title we want to render.

We also have a meta property set to an array to set the meta tag data.

As a result, we should see the title of the page set to My Title and:

<meta name="description" content="My description">

rendered in the head tag.

We can also install by running npm install vue-head --save and register it with:

import Vue from 'vue'
 
Vue.use(VueHead)
//...

Then we can follow the same steps as before.

Conclusion

To inject elements into the head element with Vue.js and JavaScript, we can use the vue-head library.