Vue 中 $attrs 與 $listeners 的詳解


介紹

$attrs

繼承所有的父組件屬性(沒有通過 props 接收的屬性還有 class 類名 和 style 樣式 )。

inheritAttrs:

是否非 props 屬性顯示在標簽最外層,默認值 true ,就是繼承所有的父組件屬性(除了 props 特定綁定外)作為普通的 HTML 特性應用在子組件的根元素上,如果你不希望組件的根元素繼承特性就設置 inheritAttrs: false ,但是 class 還是會繼承。

$listeners

它是一個對象,能接收所有的方法綁定,里面包含了作用在這個組件上的所有監聽器,配合 v-on="$listeners" 將所有的事件監聽器指向這個組件的某個特定的子元素。前端培訓

舉例

父組件中

 
<template>
<div id="app">
<Son src="https://img01.yzcdn.cn/vant/logo.png"></Son>
</div>
</template>

<script>
import Son from "./components/son.vue";
export default {
name: "App",
components: {
Son,
},
};
</script>

<style></style>
 
 
 
復制代碼
 

子組件中

 
<template>
<div id="app">
<Son src="https://img01.yzcdn.cn/vant/logo.png"></Son>
</div>
</template>

<script>
import Son from "./components/son.vue";
export default {
name: "App",
components: {
Son,
},
};
</script>

<style></style>
 
 
 
復制代碼
 

可見,當 inheritAttrs 默認 false 時,屬性是傳入到子組件最外層的

 

當 inheritAttrs 為 true 后

 

當使用 props 接收屬性時,屬性就不會被顯示

 

總結:組件標簽上傳入的屬性如果子組件沒有接收會跑到子組件標簽最外層。

非 props 屬性可以通過 $attrs 接收 {屬性名:屬性值}

 
<template>
<div>
<img v-bind="$attrs" alt="" />
</div>
</template>

<script>
export default {
inheritAttrs: false,
};
</script>
<style scoped>
.img {
width: 100px;
height: 100px;
}
</style>
 
 
 
復制代碼
 

當給子組件綁定點擊事件時,是不會觸發點擊事件的,可以使用 .native 修飾符進行綁定成功

 

或者通過 $listeners 進行接收所有方法的綁定

子組件內

 

結果

 

總結 :

所有非 props 屬性都可以通過 $attrs 接收

使用:v-bind="$attrs" 將所有非 props 屬性綁定到相應標簽,也可以用於組件

所有組件上的方法綁定子組件都可以通過 $listeners 接收

使用:v-on="$listeners"將所有方法又綁定到組件相應標簽,也可以用於組件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM