一 什么是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> ?等 |