vue3中的 $attrs 與 Attributes 繼承
vue3中的 $attrs 與 Attributes 繼承
官方文檔:https://cn.vuejs.org/guide/components/attrs.html#attribute-inheritance
首先介紹一下什么是 Attributes 繼承,即屬性繼承!
當一個父組件給子組件綁定屬性時(props屬性、class屬性、自定義事件、style屬性等等)
// 父組件 <Demo @click="fn1" @getname="fn2" numm="111" :name="slotName" class="abc" > </Demo>
子組件的根元素(即最外層的元素)會自動繼承除去 props
、emits
之外的屬性
而這些屬性都被封裝到了 $attrs
對象上
// demo.vue <template> <div> {{ $attrs }} </div> </template> <script setup> import { ref, useAttrs } from 'vue' const props = defineProps({ name: String }) let attrs = useAttrs() console.log(attrs) </script>
attrs = Proxy {numm: ‘111’, class: ‘abc’, __vInternal: 1, onClick: ƒ, onGetname: ƒ}
$attrs:
這個 $attrs
對象包含了除組件所聲明的 props
和 emits
之外的所有其他 attribute,例如 class
,style
,v-on
監(jiān)聽器等等。
禁用 Attributes 繼承:取消根節(jié)點自動繼承
// 需要額外加上一個配置 <script> export default { inheritAttrs: false, } </script> <script setup> import { ref, useAttrs } from 'vue' const props = defineProps({ name: String }) ref(12) let attrs = useAttrs() console.log(attrs) </script>
v-bind=$attrs
實現(xiàn)孫組件的 Attribute 繼承
我們想要所有的透傳 attribute 都應用在內(nèi)部的元素中, 而不是外層的根節(jié)點上。我們可以通過設定 inheritAttrs: false
和使用 v-bind="$attrs"
來實現(xiàn)
<div class="btn-wrapper"> <button class="btn" v-bind="$attrs">click me</button> </div>
沒有參數(shù)的
v-bind
會將 $attrs 的所有屬性都作為 attribute 應用到目標元素上
到此這篇關于vue3中的 $attrs 與 Attributes 繼承的文章就介紹到這了,更多相關vue3 $attrs 與 Attributes 繼承內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue.js出現(xiàn)Vue.js?not?detected錯誤的解決方案
這篇文章主要介紹了vue.js出現(xiàn)Vue.js?not?detected錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09