Vue $attrs 物件
示例
使用 $attrs
物件將 id
透傳屬性定向到 <p>
標籤。
<template>
<h3>Tigers</h3>
<img src="/img_tiger_small.jpg" alt="tiger">
<p v-bind="$attrs">Tigers eat meat and not plants, so they are called carnivores.</p>
</template>
執行示例 »
更多示例請參見下方。
定義和用法
$attrs
物件代表了設定在元件標籤上的透傳屬性和事件監聽器。
當希望根元素繼承設定在元件標籤上的透傳屬性和事件監聽器時,我們在根元素上使用 v-bind="$attrs"
。
$attrs
物件是隻讀的。
透傳屬性是在元件標籤上設定的(非 props)屬性,這些屬性會透傳到元件的根元素。如果元件有多個根元素,則使用 $attrs
物件來指定哪個元素應該繼承透傳屬性。 在教程中瞭解更多關於透傳屬性的資訊。
更多示例
示例 1
使用 $attrs
物件顯示透傳屬性 id
和 title
及其值。
<template>
<h3>Tigers</h3>
<img src="/img_tiger_small.jpg" alt="tiger">
<p v-bind="$attrs">Tigers eat meat and not plants, so they are called carnivores.</p>
<hr>
<p><strong>Below is the content of the $attrs object:</strong></p>
<pre>{{ attrsObject }}</pre>
</template>
<script>
export default {
data() {
return {
attrsObject: null
}
},
mounted() {
console.log(this.$attrs);
this.attrsObject = this.$attrs;
}
}
</script>
<style>
#pink {
background-color: pink;
border-radius: 15px;
padding: 10px;
}
img {
width: 100%;
border-radius: 15px;
}
</style>
執行示例 »
示例 2
在 <img>
標籤上使用 $attrs
物件來接收父元件的事件監聽器。
<template>
<h3>Toggle Image Size</h3>
<p>Click the image to toggle the image size.</p>
<img v-bind="$attrs" src="/img_tiger_small.jpg" class="imgSmall">
</template>
<style>
.imgSmall {
width: 60%;
}
.imgLarge {
width: 100%;
}
img {
border-radius: 15px;
cursor: pointer;
}
</style>
執行示例 »
相關頁面
Vue 教程:Vue 透傳屬性
Vue 教程: Vue 方法
Vue 教程:Vue v-bind 指令
Vue 教程: Vue v-on 指令
Vue 參考:Vue v-bind 指令
Vue 參考:Vue v-on 指令