在vue中使用inheritAttrs實現組件的擴展性介紹
1、首先我們創建一個input組件
<template> <div class='inputCom-wrap'> <input v-bind='$attrs' /> </div></template> <script lang='ts'>import { defineComponent } from ’vue’ export default defineComponent({ inheritAttrs:false,//不希望根直接繼承特性,而是使用$attrs自定義繼承,當前組件的根就是inputCom-wrap setup () { return {} }})</script> <style scoped> </style>
2、使用組件的時候,隨便增加一些屬性,如
<inputCom type='text' class='input-a'></inputCom>
<inputCom type='password' class='input-b'></inputCom>
3、查看最終的渲染結果為(與props不會沖突)
補充知識:vue組件深層傳值inheritAttrs、$attrs、$listeners
1、$attrs
組件深層傳值 可通過父組件綁定 v-bind='$attrs'傳給子組件
一般子組件this.$attrs可以拿到父組件的所有傳輸的屬性。
當子組件props注冊了聲明某屬性之后,this.$attrs將不包含該屬性;
同理通過v-bind='$attrs'綁定孫子組件也不會包含子組件props聲明的屬性。
props: { data:{ type: Array, default: () => [],//數組格式[{label:xx,value:xxx}] }, value: { type: Array, default: () => [],//數組格式[xx,xx,xx] }, maxHeight:{ type:[String,Number], default:350, } },mounted() { console.log('來自多選',this.$attrs) },
2、inheritAttrs
默認值為true
默認情況子組件props未聲明,父組件傳輸的其他屬性會被認作 props 的 attribute 綁定 (attribute bindings) 將會“回退”且作為普通的 HTML attribute 應用在子組件的根元素上(有可能會覆蓋子組件根元素上的某些屬性列如 type='text'之類屬性)
子組件的inheritAttrs 設置為false可以避免
3、$listeners
父組件-子組件-孫子組件,現在我要你在孫子組件里改變父組件的值,子組件直接綁定
<muti-select v-bind='$attrs' v-on='$listeners' class='select'></muti-select>
以上這篇在vue中使用inheritAttrs實現組件的擴展性介紹就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: