Provide and inject

Allows an ancestor component to inject a dependency into all of its descendants, no matter how deep the component hierarchy, for as long as its upstream and downstream relationships are established.

Usually parent and child components pass values

  • Generally, it is received through the props attribute. Once there are too many layers of components, it is very troublesome to pass the value level by level in this way, and the code is not readable enough for later maintenance.
  • Vue provides provide and Inject to help us solve multi-level nested nested communication problems. Specify data to be passed to descendant components in provide, which inject data passed by the parent component.

Dojo.provide and inject

  1. Provide: is an object, or a function that returns an object. Contains things to pass on to posterity, namely properties and property values. Note: The descendant’s provide obscures the property values of the same key in the grandparent’s provide
 provide: {
    foo: 'bar'
  },
Copy the code
  1. Inject: An array of strings, or an object.
  • The property value can be an object containing the default values from and default
  • From is the key (string or Symbol) to search for in the available injection content
  • Default is the value used in degraded cases
// Parent component provides 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// Inject 'foo' into the subcomponent
var Child = {
  inject: ['foo'],
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}
Copy the code

For example,

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>provide + inject</title> <script SRC = "https://cdn.bootcss.com/vue/2.6.11/vue.min.js" > < / script > < / head > < body > < div id = "app" > < / div > < / body > < / HTML > <script> Vue.component('A', { template: ` <div> <B></B> </div> `, provide: { msg: '1234124' } }) Vue.component('B', { template: ` <div> <label>B:</label> <span>{{ this.msg }}</span> <C></C> </div> `, provide: { msg: '42341234', name: 'asdasda' }, inject: ['msg'], }) Vue.component('C', { template: ` <div> <label>C:</label> <span>{{ this.xingming }}</span> <span>{{ this.msg }}</span> </div> `, inject: { xingming: { from: 'name', default: '' }, msg: { from: 'msg', default: '' } }, data() { return { } }, }) var app=new Vue({ el: '#app', template: ` <div> <A /> </div> ` }); </script>Copy the code

advice

Direct use in application code is not recommended because it is difficult to track the data, not knowing which level declares this or which level or levels are used.