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; val...

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:

2. Code:

<template> <div> <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: }, 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

19 January 2020, 11:26 | Views: 3967

Add new comment

For adding a comment, please log in
or create account

0 comments