Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 attrs

作者:ンц枫飄落   发布日期:2026-07-17   浏览:95

// Vue 3 中的 attrs 示例

<template>
  <div>
    <!-- 将所有未被 props 捕获的 attribute 绑定到子组件上 -->
    <child-component v-bind="$attrs"></child-component>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default defineComponent({
  name: 'ParentComponent',
  components: {
    ChildComponent,
  },
  inheritAttrs: false, // 禁用属性继承,防止未被 props 捕获的 attribute 被绑定到当前组件的根元素上
});
</script>

<!-- 子组件 -->
<template>
  <div>
    <!-- 使用 $attrs 获取所有未被 props 捕获的 attribute -->
    <p>Attributes: {{ $attrs }}</p>
  </div>
</template>

<script>
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'ChildComponent',
  props: {
    // 定义一些 props
    message: String,
  },
  setup(props) {
    console.log(props.message); // 访问传递给子组件的 message prop
    console.log(this.$attrs);   // 访问所有未被 props 捕获的 attribute
  },
});
</script>

解释说明:

  1. v-bind="$attrs":在父组件中使用 v-bind="$attrs" 可以将所有未被 props 捕获的 attribute 绑定到子组件上。这通常用于高阶组件或需要透传属性的场景。

  2. inheritAttrs: false:默认情况下,Vue 会将所有未被 props 捕获的 attribute 绑定到当前组件的根元素上。通过设置 inheritAttrs: false,可以禁用这一行为,从而更好地控制这些 attribute 的去向。

  3. $attrs:在子组件中,$attrs 是一个对象,包含了所有未被 props 捕获的 attribute。你可以通过 $attrs 来访问这些 attribute,并根据需要进行处理。

  4. props:定义了 props 后,传递给子组件的属性会被自动捕获并赋值给 props,而未被 props 捕获的 attribute 则会存储在 $attrs 中。

希望这个示例能帮助你理解 Vue 3 中 attrs 的用法。

上一篇:vue3 script setup语法糖

下一篇:vue父子组件传值props

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站