vue notes-provide & inject (2)

1. Usage:

  • provide: Used in ancestor components; a value is an object or a function that returns an object;
  • inject: Used in descendant components; value is an array of keys or an object in the provider object whose key value is the local binding name and value is the key or an object in the provider object: {from:'key in the provider object', default:'default value, used for demotion processing'}

2. Code:

<template>
  <div class="menu">
    <root-menu>
      <child-menu>
         <sun-menu></sun-menu>
      </child-menu>
    </root-menu>
  </div>
</template>

<script>
import Vue from 'vue'

Vue.component('RootMenu',{
  provide:{
    a:'RootMenu',
    b:{name:'RootMenu'}
  },
  render: function (createElement) {
    return createElement(
      'div',   // Tag name tag name
      this.$slots.default // Arrays in subcomponents
    )
  },
})

Vue.component('ChildMenu',{
  inject:{
    localName:'a'
  },
  provide:{
    c:'ChildMenu'
  },
  render: function (createElement) {
    return createElement(
      'div',   // Tag name tag name
      [
        this.getLocalName(),
        createElement('a',this.$slots.default)
      ]
    )
  },
  methods:{
    getLocalName(){
      return this.localName + 'Submenu';
    }
  }
})

Vue.component('SunMenu',{
  inject:['b','c'],
  render: function (createElement) {
    return createElement(
      'div',   // Tag name tag name
      [
        this.getLocalName(),
        createElement('a',this.$slots.default)
      ]
    )
  },
  methods:{
    getLocalName(){
      return this.b.name + 'Sun Menu'+this.c;
    }
  }
})

export default {
 data(){
   return {};
 }
}
</script>

3. Result:

4. Description:

  • Inj in a component can include provide content from each parent component
  • Local Binding Name in 1 refers to a name that can be customized

Tags: Vue

Posted on Sun, 19 Jan 2020 11:26:32 -0500 by omprakash