vue3 随手笔记12--组件通信方式9/5--useAttrs
·
一 什么是useAttrs
useAttrs 是 Vue 3 Composition API 中提供的一个函数,它属于 Vue 的组合式 API 工具集的一部分。通过 useAttrs,你可以访问传递给组件但未被声明为 props 的所有属性。这对于处理非 prop 特性(attributes)特别有用,比如 HTML 特性或自定义数据特性等。
它返回的是一个响应式对象,包含了父组件传递下来的所有非 prop 属性(如 class, style, id, data-* 等 HTML 原生属性),以及监听器(如 @click, @input 等)。
使用场景
- 当你需要获取没有在
props中声明的属性时。 - 在需要将属性透传(attribute inheritance)到子组件或根元素时非常有用。
二 基本使用
需要引用element-plus
npm install element-plus --save
main.js中引用element-plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)
父组件Parent.vue
<template>
<div class="props-text">
<h1>useAttrs</h1>
<!--useAttrs() 是 Vue 3 Composition API 中的一个函数,
用于访问当前组件的 非 props 属性(non-prop attributes)。
这些属性通常包括 class、style、id、原生 HTML 属性等。
-->
<h1>我是父组件</h1>
<el-button type="primary" size="small" :icon="Edit"></el-button>
<hr>
<CustomButton type="primary" size="small" :icon="Edit" title="编辑" @click="handler"></CustomButton>
</div>
</template>
<script setup>
//引入图标按钮 网址:https://element-plus.org/zh-CN/component/button.html
import {
Check,
Delete,
Edit,
Message,
Search,
Star,
} from '@element-plus/icons-vue'
import CustomButton from './CustomButton.vue';
const handler = () => {
console.log('点击了按钮');
}
</script>
<style scoped>
.props-text {
width: 400px;
height: 400px;
background-color: burlywood;
}
</style>
自定义按钮组件CustomButton.vue
<template>
<div>
<el-button v-bind="$attrs"></el-button>
<el-button :="$attrs"></el-button>
<el-button :type="$attrs.type" :size="$attrs.size" :icon="$attrs.icon"></el-button>
</div>
</template>
<script setup>
import { useAttrs } from 'vue';
let $attrs = useAttrs();
let props = defineProps(['title'])
console.log(props.title);
console.log($attrs);
//同时使用 $attrs 和 props 优先props 会导致 $attrs.title 丢失
</script>
<style></style>
三 注意事项
| 注意点 | 说明 |
|---|---|
| 🔁 响应性 | attrs 是响应式的,但其值不会触发模板重新渲染。 |
| 🧠 非响应式数据 | 不要试图用 attrs 来驱动响应式逻辑(比如 computed 或 watch) |
| 🧹 清理属性 | 如果你不希望某些属性被继承,应该使用 inheritAttrs: false 并手动绑定需要的属性 |
| 🧑🔧 自定义组件开发 | 常用于封装可复用的基础组件,如 <MyInput>, <BaseButton> 等 |
更多推荐



所有评论(0)