Subscribe on changes!

Events are not found in `useAttrs`

avatar
Feb 2nd 2023

Vue version

3.2.45

Link to minimal reproduction

https://stackblitz.com/edit/vue-3-events-notinattrs?file=src%2FTest.vue

Steps to reproduce

According to the Vue 3 Migration Documentation https://v3-migration.vuejs.org/breaking-changes/listeners-removed.html#overview the $listeners is removed and we have to use useAttrs but useAttrs doesn't provide the events specified for the Component

<Test @dismiss="handler" />
const attrs = useAttrs()
attrs.onDismiss // ERROR: this is not found

What is expected?

To get events list as defined in https://v3-migration.vuejs.org/breaking-changes/listeners-removed.html#_3-x-syntax

What is actually happening?

Events are missing, only attributes are part of useAttrs

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 16.14.2 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 7.17.0 - /usr/local/bin/npm
  npmPackages:
    vue: ^3.2.25 => 3.2.31

Any additional comments?

No response

avatar
Feb 2nd 2023

When you declare an event in defineEmits, it will be removed from the $attrs because it is stored internally elsewhere.

Duplicate https://github.com/vuejs/core/issues/5319

There is no official API for getting declared events passed from the parent component, I don't know if this is something that is planned to be added, but here https://github.com/vuejs/core/issues/5220#issuecomment-1007602686 I've shown some workaround for this (use at your own risk, may break down at any time)

avatar
Feb 2nd 2023

Events that are not declared are part of attrs. Declared component events are not, because by default, all attrs are passed on to a component's root element, and you likely don't want your declared events to be added as a listener on some div.

the simplest way to deal with that is to just wrap the emit function for the event(s).

const onClose = (...args) => emit('close', ...args)

and combine that with the attrs where needed.

If you think this should be added to the docs, feel free to start a discussion on the docs repo.

avatar
Feb 2nd 2023

Yes, definitely the docs need to be updated then. All confusion was because of the docs

If you think this should be added to the docs, feel free to start a discussion on the docs repo.

Yes, will do that