Home > Software design >  How to correctly listen to an event in Vue 3 using TS?
How to correctly listen to an event in Vue 3 using TS?

Time:10-14

Component code:

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

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

Typescript error:

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>'

What is the problem?

CodePudding user response:

We were facing the same problem - all event handlers in template are erroneous. It appeared a few days ago. Based on the typescript definition, the event handler must return types "Event" or "MouseEvent". Therefore, we have corrected it in the template as follows:

<h2 @click="(e : MouseEvent) => {handleEvent(post.id); return e;}">{{ post.title }}</h2>

It works, but does not seem to be the way how event handlers should be written...

CodePudding user response:

As I understand in this issue we have 2 options:

  1. add @types/node: '18.8.0'
  2. wait until this change is merged into a vue 2.7 release

note: Don't use the ^, fix the version to 18.0.0

I install the @types/node fixed version and works for me.

  • Related