菜单
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue 教程

Vue 首页 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue:为何、如何以及设置 Vue:第一个 SFC 页面 Vue 组件 Vue Props Vue v-for 组件 Vue $emit() Vue 透传属性 Vue 作用域样式 Vue 本地组件 Vue 插槽 Vue v-slot Vue 作用域插槽 Vue 动态组件 Vue Teleport Vue HTTP 请求 Vue 模板引用 Vue 生命周期钩子 Vue Provide/Inject Vue 路由 Vue 表单输入 Vue 动画 Vue v-for 动画 Vue 构建 Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

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 对象显示透传属性 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

<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 指令


×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持