Subscribe on changes!

Event payloads emitted by a Custom Element are always wrapped in an array inside CustomEvent.detail

avatar
Jan 25th 2022

Version

3.2.29

Reproduction link

codesandbox.io

On the provided Sandbox if you get a Syntax Error on load, just click the included refresh button and it should load properly.

Steps to reproduce

  1. Create a new Vue Component with defineComponent that emits an event.
  2. Wrap the element with with defineCustomElement and then register it as a custom element with customElement('custom-button', CustomButton)
  3. Run your app, and click the custom element button on the page to trigger an emit.
  4. View the payload inside CustomEvent.detail in the console, or in the output on the page.

What is expected?

CustomEvent.detail should equal { email: 'playerone@email.com' }

What is actually happening?

The payload inside CustomEvent.detail is wrapped in an array, outputting [{ email: 'playerone@email.com' }] which is unexpected.

avatar
Jan 25th 2022

Vue events can have more than one argument,

this.$emit('event', 1, 2, 3)

but CustomEvent only has one payload: event.detail

new CustomEvent({
  detail: [1, 2, 3]
})

So we have to use an array in case a component wants to emit more than one thing.

it's also documented in the new doc we will launch of Feb 9th.

https://staging.vuejs.org/guide/extras/web-components.html#events

avatar
Jan 25th 2022

@LinusBorg thanks for the quick response!

All extra arguments passed to $emit() after the event name will be forwarded to the listener. For example, with $emit('foo', 1, 2, 3) the listener function will receive three arguments.

This appears to be missing from the live version of the docs 🤷🏼‍♂️ -- I've never seen that formally outlined in the Vue 2/3 docs.

avatar
Jan 25th 2022

You mean like this? 🤔

https://v3.vuejs.org/api/instance-methods.html#emit

Vue 2 docs have basically the same sentence as well.

avatar
Jan 25th 2022

😂 yep, exactly like that.