inject 和 provider 是vue中的组合选项,需要一起使用。目的是允许一个祖先组件向其所有子孙后代注入依赖(简单地说就是祖先组件向子孙后代传值的一种方法,祖先组件通过provider提供变量,子孙后代通过inject注入接收变量)
provider: Object || () => Object
inject: Array || Object
Eg.
button.vue:
1 <template> 2 <button 3 class="el-button" 4 @click="handleClick" 5 :disabled="buttonDisabled || loading" 6 :autofocus="autofocus" 7 :type="nativeType" 8 :class="[ 9 type ? 'el-button--' + type : '', 10 buttonSize ? 'el-button--' + buttonSize : '', 11 { 12 'is-disabled': buttonDisabled, 13 'is-loading': loading, 14 'is-plain': plain, 15 'is-round': round, 16 'is-circle': circle 17 } 18 ]" 19 > 20 <i class="el-icon-loading" v-if="loading"></i> 21 <i :class="icon" v-if="icon && !loading"></i> 22 <span v-if="$slots.default"><slot></slot></span> 23 </button> 24 </template> 25 <script> 26 export default { 27 name: 'ElButton', 28 29 // 通过inject向button中注入变量 30 inject: { 31 elForm: { 32 default: '' 33 }, 34 elFormItem: { 35 default: '' 36 } 37 }, 38 39 props: { 40 type: { 41 type: String, 42 default: 'default' 43 }, 44 size: String, 45 icon: { 46 type: String, 47 default: '' 48 }, 49 nativeType: { 50 type: String, 51 default: 'button' 52 }, 53 loading: Boolean, 54 disabled: Boolean, 55 plain: Boolean, 56 autofocus: Boolean, 57 round: Boolean, 58 circle: Boolean 59 }, 60 61 computed: { 62 _elFormItemSize() { 63 return (this.elFormItem || {}).elFormItemSize; 64 }, 65 buttonSize() { 66 return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size; 67 }, 68 buttonDisabled() { 69 return this.disabled || (this.elForm || {}).disabled; // 通过inject注入的form变量,获得祖先节点form的disabled属性 70 } 71 }, 72 73 methods: { 74 handleClick(evt) { 75 this.$emit('click', evt); 76 } 77 } 78 }; 79 </script>