類型:數組
Object | () => Object
Array<string> | { [key: string]: string | Symbol | Object }
這對選項須要一塊兒使用,以容許一個祖先組件向其全部子孫後代注入一個依賴,不論組件層次有多深(也就是父級如下全部子組件均可以經過inject獲得父組件的數據),並在起上下游關係成立的時間裏始終生效。 ide
provide
是一個對象或返回一個對象的函數。該對象包含可注入其子孫的屬性, 函數
inject
選項是:this
from
屬性是在可用的注入內容中搜索用的 key (字符串或 Symbol)default
屬性是降級狀況下使用的 value這裏舉栗子 elementUI breadcrumb組件源代碼spa
1 <template> 2 <div class="el-breadcrumb" aria-label="Breadcrumb" role="navigation"> 3 <slot></slot> 4 </div> 5 </template> 6 <script> 7 export default { 8 name: 'ElBreadcrumb', 9 10 props: { 11 separator: { 12 type: String, 13 default: '/' 14 }, 15 separatorClass: { 16 type: String, 17 default: '' 18 } 19 }, 20 21 provide() { 22 return { 23 elBreadcrumb: this 24 }; 25 }, 26 27 mounted() { 28 const items = this.$el.querySelectorAll('.el-breadcrumb__item'); 29 if (items.length) { 30 items[items.length - 1].setAttribute('aria-current', 'page'); 31 } 32 } 33 }; 34 </script>
子組件將獲取到父組件的this,這樣就能夠獲得父組件的數據 code
1 <template> 2 <span class="el-breadcrumb__item"> 3 <span 4 :class="['el-breadcrumb__inner', to ? 'is-link' : '']" 5 ref="link" 6 role="link"> 7 <slot></slot> 8 </span> 9 <i v-if="separatorClass" class="el-breadcrumb__separator" :class="separatorClass"></i> 10 <span v-else class="el-breadcrumb__separator" role="presentation">{{separator}}</span> 11 </span> 12 </template> 13 <script> 14 export default { 15 name: 'ElBreadcrumbItem', 16 props: { 17 to: {}, 18 replace: Boolean 19 }, 20 data() { 21 return { 22 separator: '', 23 separatorClass: '' 24 }; 25 }, 26 27 inject: ['elBreadcrumb'], 28 29 mounted() { 30 this.separator = this.elBreadcrumb.separator; 31 this.separatorClass = this.elBreadcrumb.separatorClass; 32 const link = this.$refs.link; 33 link.setAttribute('role', 'link'); 34 link.addEventListener('click', _ => { 35 const { to, $router } = this; 36 if (!to || !$router) return; 37 this.replace ? $router.replace(to) : $router.push(to); 38 }); 39 } 40 }; 41 </script>