You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3中无法将函数作为Prop传递给子组件的问题求助

问题分析与解决方案

你遇到的问题核心是Vue中prop的大小写命名规范不匹配导致方法无法正确传递,下面一步步拆解并解决:

问题根源

HTML的属性名是大小写不敏感的,当你在父组件模板中写:SiteToEdit="EditSite"时,浏览器会自动把这个属性名转换为全小写的sitetoedit。而你的子组件props中定义的是SiteToEdit(驼峰命名),Vue无法将小写的sitetoedit映射到驼峰的SiteToEdit,最终导致props.SiteToEdit是undefined,调用时自然会报错“不是函数”。

修复方案

按照Vue的官方规范,我们需要在模板中使用**kebab-case(短横线分隔)传递prop,在组件的props选项中使用camelCase(驼峰)**接收,Vue会自动完成两者的映射。

步骤1:修改父组件的prop传递方式

把:SiteToEdit改成:site-to-edit:

<template>
  <div class="grid-item">
    <SiteCmpnt :sID="'Z'" :site-to-edit="EditSite"></SiteCmpnt>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import SiteCmpnt from './SiteCmpnt.vue' // 确保正确引入子组件

export default defineComponent({
  components: { SiteCmpnt },
  setup() {
    const EditSite = (siteID) => {
      console.log("I'm ready to edit site: ", siteID)
    }
    return { EditSite }
  }
})
</script>

步骤2:子组件简化代码(可选优化)

你的子组件props定义是正确的(驼峰命名),不需要修改,还可以省去中间的包装函数,直接在模板中调用父组件传递的方法:

<template>
  <div class="sbs2">
    <Icon name="edit" @click="SiteToEdit(sID)"/>
  </div>
</template>

<script>
export default {
  props: {
    sID: String,
    SiteToEdit: Function
  }
}
</script>

验证效果

现在点击编辑图标,控制台应该会正确输出:

I'm ready to edit site:  Z

如果还是有问题,可以检查以下几点:

  • 确保父组件正确引入了子组件
  • 确认子组件的Icon组件已正确注册,@click事件能正常触发
  • 在子组件的setup中打印props,确认SiteToEdit是否存在:
    setup(props){
      console.log(props) // 查看props是否包含SiteToEdit方法
      // ... 其他代码
    }
    

内容的提问来源于stack exchange,提问作者user2728963

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:37:34