Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting into <head> in Vue.js

I have a few EXTERNAL scripts that need to be loaded on various pages, such as Google Places Autocomplete, Facebook APIs, etc.

Obviously it does not make sense to load them on every route, however the documentation does not address this rather common scenario.

Furthermore, the Vue instance mounts onto a tag within the body, since

the mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to < html > or < body >.

How are real world applications currently dealing with this situation?

like image 347
softcode Avatar asked Jan 18 '17 03:01

softcode


People also ask

What is inject in Vue JS?

The inject API is a function we use to receive data from our provider component. As we did with the provide function, we also have to import the inject function from vue . This lets us call and use the function anywhere in our component. The inject function takes two parameters: The name of the property being injected.

Does Vue use dependency injection?

To handle dependency injection in Vue, the provide and inject options are provided out of the box.

How do I stop Prop drilling at Vue?

In order to avoid props drilling, I want to use provide/inject. In the root component in the setup function, I use provide . In the child component in the setup function, I get the value via inject .


1 Answers

I recommend using https://www.npmjs.com/package/vue-head, it is exactly designed to inject the data you want from your component into the document's head. Perfect for SEO title and meta tags.

To be used like so:

export default {   data: () => ({     title: 'My Title'   }),    head: {     // creates a title tag in header.     title () {       return {         inner: this.title       }     },     meta: [       // creates a meta description tag in header.       { name: 'description', content: 'My description' }     ]   } } 
like image 89
antoni Avatar answered Oct 03 '22 00:10

antoni