Built-in support

Unfortunately, out of the box, Vue doesn't provide much support for dependency injection in its current version.

However, Vue does include two options: provide and inject. They are described in the official documentation (https://vuejs.org/v2/api/#provide-inject). These two options are normally intended for plugin development, but can actually be used in any Vue application. We'll see that we can leverage them in our applications to define/provide dependencies and inject them where needed.

Through the provide option, components can define elements that can be injected into any of their descendants using inject.

This feature is quite similar to the providers array in Angular. As a matter of fact, it is also close to React's context feature, which we'll talk about later in this book.

We can also use inject to get access to injectable elements.

Here's a basic example of using the more classic Vue syntax:

// a parent component provides 'foo' 
var Provider = { 
  provide: { 
    foo: 'bar' 
  }, 
  // ... 
} 
 
// a child component injects 'foo' 
var Child = { 
  inject: ['foo'], 
  created () { 
    console.log(this.foo) // => "bar" 
  } 
  // ... 
} 

As you can see, it isn't too complicated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.28.48