博文

Vue 3 透传 Attributes 第四章:$attrs 对象的深度理解与应用

扫描 二维码 关注或者微信搜一搜: 编程智域 前端至全栈交流与成长 发现 1000+ 提升效率与开发的 AI 工具和实用程序 : https://tools.cmdragon.cn/ 一、$attrs 对象的结构与内容 1.1 $attrs 是什么 $attrs 是一个包含组件所有 未声明 的 attributes 的对象。具体来说,以下 attributes 会进入 $attrs : 未在 props 中声明的属性 未在 emits 中声明的事件监听器 所有 HTML 标准属性(class、style、id 等) 自定义属性(data- 、aria- 等) 不包括 : 已在 props 中声明的属性 已在 emits 中声明的事件(Vue 3 中会从 $attrs 中移除) 1.2 $attrs 的结构示例 <!-- 父组件 --> < template >   < ChildComponent     title = "标题"     class = "my-class"     id = "my-id"     data-foo = "bar"     @click = "handleClick"     @custom-event = "handleCustom"   /> </ template > <!-- 子组件 --> < script setup > import { onMounted , useAttrs } from 'vue' ​ const attrs = useAttrs () ​ onMounted (() => {   console . log ( '$attrs:' , attrs )   // 输出:   // {   //   class: 'my-class',   //   id: 'my-id',   //   'data-foo': 'bar', ...