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

Vue3监听click事件时出现TypeScript类型不兼容错误咨询

Vue3+TypeScript事件绑定类型错误原因分析

组件代码

<h2 @click="handleEvent(post.id)">{{ post.title }}</h2>

function handleEvent(id: number) {
  router.push("/post/" + id);
}

触发的TypeScript错误

Type '($event: any) => void' is not assignable to type 'MouseEvent'.ts(2322)
__VLS_types.ts(107, 56): The expected type comes from property 'click' which is declared here on type 'EventObject<undefined, "click", {}, MouseEvent | undefined>'

错误原因

  • Vue模板的事件绑定逻辑中,直接写@click="handleEvent(post.id)"时,会被自动包装成一个匿名箭头函数,等价于:
    @click="($event) => handleEvent(post.id)"
    
  • Vue的点击事件处理函数,默认要求符合(event: MouseEvent) => void的类型(也可以是不接收参数的函数)。
  • 你定义的handleEvent仅接受number类型参数,此时自动生成的匿名函数类型,和Vue期望的事件处理函数类型不匹配,TypeScript因此抛出类型不兼容的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:55:15