Vue $attrs 对象


示例

使用$attrs反对指导idFallthrough 属性为<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对象表示组件标签上设置的fallthrough属性和事件侦听器。

我们用v-bind="$attrs"当我们希望该元素继承组件标记上设置的fallthrough属性和事件侦听器时,在根元素上。

这个$attrs对象是只读的。

坠落属性是在组件标签上设置的属性(不是 props),它会传递到组件的根元素。如果组件中有多个根元素,我们使用$attrsobject 指定哪个元素应该继承fallthrough 属性。在教程中了解有关 Fallthrough 属性的更多信息。


更多示例

示例1

使用$attrs显示 Fallthrough 属性的对象idtitle,以及他们的值。

<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

使用$attrs对象在<img>标签用于从父组件接收事件侦听器。

<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 Fallthrough 属性

Vue教程:Vue 方法

Vue教程:Vue v-bind 指令

Vue教程:Vue v-on 指令

Vue参考:Vue v-bind 指令

Vue参考:Vue v-on 指令