Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to a Vue event from Vanilla JavaScript

I have a Vue component which emits the change event.

  methods: {
    onSelect(value) {
      this.open = false
      if (value === this.value) return
      this.$emit('change', value)
    },
  }

I am importing this component into an .astro component. (basically Vanilla JS/HTML)

  <VisSelect client:load brand={brand} name={selectId} placeholder={placeholder} label={label} required={required} options={options} />

I am adding an event listener to my document (tried different selectors, including the selector under which the component is mounted) listening to change but it's not fired.

document.addEventListener('change', (e) => console.log(e))
like image 693
George Katsanos Avatar asked Nov 27 '25 14:11

George Katsanos


1 Answers

You can try like with the web-components, create ref to the top div (for example selected) and dispatch CustomEvent:

onSelect(value) {
  this.open = false
  if (value === this.value) return
  this.$refs.selected.dispatchEvent(
    new CustomEvent('change', {
      detail: { value },
      bubbles: true,
      composed: true,
    })
  );
}

and then get the datail You provided in the event:

document.addEventListener('change', (e) => console.log(e.detail))
like image 108
Nikola Pavicevic Avatar answered Nov 30 '25 02:11

Nikola Pavicevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!