Vue $attrs 对象
实例
使用 $attrs 对象将 id fallsthrough 贯穿属性定向到 <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 对象表示在 component 标记上设置的贯穿属性和事件监听。
当我们希望根元素继承在 component 标记上设置的贯穿属性和事件监听时,我们在该元素上使用 v-bind="$attrs"。
$attrs 对象是只读的。
贯穿属性是在组件标记上设置的属性(而不是 prop),它贯穿到组件的根元素。如果组件中有多个根元素,我们使用
$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>