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