关于props和attrs 以及报错Extraneous non-props attributes (xxx) were passed to component but could not be

这个也是 之前学过,今天用到了才真正理解

父组件传递数据给子组件时:
比如:

<PrintDialog v-if="state.printDialogVisible" v-model="state.printDialogVisible" :currentClickItem="state.currentClickItem"
  :printData="state.printData" :currentClickItemId="state.currentClickItemId"></PrintDialog>

其中 currentClickItem,printData, currentClickItemId都是传过去的数据

如果子组件的defineProps为以下:

const props = defineProps({
    // currentClickItem: {
    //     type: Object,
    //     default: {}
    // },
    printData: {
        type: Object,
        default: {}
    },
    currentClickItemId:{
        type: Number,
        default: 0
    },
})

那么printData和currentClickItemId可以const { printData,currentClickItemId } = props后直接使用,或者用props.printData这样使用,而currentClickItem未被定义,则是被存储在$attrs
此时如果有1个根元素,比如:则currentClickItem会直接绑定到唯一的根元素

<template>
    <span>{{ currentClickItemId }}</span>
</template>

此时如果有多个根元素,比如:则currentClickItem不知道绑定到哪里,会报错Extraneous non-props attributes (xxx) were passed to component but could not be
此报错解决方案:
参考此博客1
参考此博客2

<template>
    <span>{{ currentClickItemId }}</span> //可以显示
    <div class="ReceiptWrap">{{ currentClickItem }}</div> //不会显示
</template>

只要修改为以下即可

<template>
    <span>{{ currentClickItemId }}</span> //可以显示
    <div class="ReceiptWrap" v-bind="$attrs">{{ $attrs.currentClickItem}}</div> //可以显示
</template>
posted @   ayubene  阅读(209)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示