1. 程式人生 > 程式設計 >Vue中$attrs與$listeners的使用教程

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.";
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",};
</script>
 
<style></style>

可見,當 inheritAttrs 預設 false 時,屬性是傳入到子元件最外層的

Vue中$attrs與$listeners的使用教程

當 inheritAttrs 為 true 後

Vue中$attrs與$listeners的使用教程

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

Vue中$attrs與$listeners的使用教程

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

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

<template>
  <div>
    <img v-bind="$attrs" alt="Vue中$attrs與$listeners的使用教程" />
  www.cppcns.com</div>
</template>
 
<script>
export default {
  inheritAttrs: false,};
</script>
<style scoped>
.img {
  width: 100px;
  height: 100px;
}
</style>

當給子元件繫結點選事件時,是不會觸發點選事件的,可以使用 .native 修飾符進行繫結成功

Vue中$attrs與$listeners的使用教程

或者通過 $listeners 進行接收所有方法的繫結

子元件內

Vue中$attrs與$listeners的使用教程

結果

Vue中$attrs與$listeners的使用教程

總結

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

使用:v-bind="$attrs" 將所有非props屬性繫結到相應標籤,也可以用於元件

所有元件上的方法繫結子元件都可以通過$listeners接收

使用:v-on="$listeners"將所有方法又繫結到元件相應標籤,也可以用於元件

到此這篇關於Vue中$attrs與$listeners的使用教程的文章就介紹到這了,更多相關Vue $attrs $listenerhttp://www.cppcns.coms內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我www.cppcns.com們!