Vue中如何传递未定义为Props的剩余属性给组件?
Vue 实现类似 React 的剩余属性传递功能
在 Vue 中,不同版本的实现方式略有差异,核心是利用内置的 $attrs 对象处理未声明为组件 Props 的属性(包括 HTML 属性、事件监听等):
Vue 3 实现
在 <script setup> 语法中,只需声明你需要的 Props,其余未声明的属性会自动被收集到 $attrs 中,直接通过 v-bind="$attrs" 绑定到内部元素即可:
<script setup> // 仅声明需要的 Props,剩余属性自动进入 $attrs const props = defineProps({ text: { type: String, default: 'Open' } }) </script> <template> <button v-bind="$attrs">{{ props.text }}</button> </template>
如果需要在脚本中单独处理剩余属性,也可以直接解构 defineProps 的返回值:
const { text, ...restProps } = defineProps(['text'])
之后在模板中使用 v-bind="restProps" 效果一致,不过 $attrs 会自动包含事件监听,使用起来更省心。
Vue 2 实现
Vue 2 默认会把未声明的属性自动绑定到组件的根元素上,如果需要手动控制绑定目标,需设置 inheritAttrs: false,再通过 $attrs 绑定到指定元素:
<script> export default { props: { text: { type: String, default: 'Open' } }, inheritAttrs: false // 关闭自动绑定到根元素的默认行为 } </script> <template> <button v-bind="$attrs">{{ text }}</button> </template>
使用示例
调用组件时,直接传入任意需要的属性或事件即可,无需在组件中逐个声明:
<CustomButton text="Open" title="Open" class="w-100" @click="handleButtonClick"></CustomButton>
内容的提问来源于stack exchange,提问作者rebinnaf
相关产品推荐
相关产品推荐

