2

I have a VueJs component on a regular web page. When it fires an event, I want the regular web page to respond. Is this possible?

Sites.vue is a single file component. It is instantiated in the middle of a regular web page

<sites @pmds="handlePmds"></sites>

From time to time, it emits an event with this:

this.$emit("pmds", pmds);

Back in the regular page, I want to handle the event like this:

    function handlePmds(e) {
      console.log(e);
    }

But that doesn't work because handlePmds is not a VueJS function. So how do I catch that event?

4
  • What do you plan to do with the pmds data? Commented Dec 29, 2020 at 23:32
  • I want to use it to populate a jQuery autocomplete box. So the user picks a site using the <site></site> and when they do, it emits an event so that the jQuery autocomplete gets a list of label/value pairs. Commented Dec 29, 2020 at 23:35
  • I think you need to add a bit more info to your question. Otherwise, it's hard to answer. As far as I know, you can't directly listen to an emitted Vue event, but you can set the data to an external variable. So, it really depends on how you're using it in this autocomplete box. Commented Dec 29, 2020 at 23:41
  • I could conceivably populate a hidden html input, but that wouldn't give me the notification to fill the autocomplete. Commented Dec 30, 2020 at 0:09

1 Answer 1

3

First, create a plain JS CustomEvent in one of the vueJS methods. The payload data goes in the second argument in a field called detail

methods: {
  sendPmds() {
    let event = new CustomEvent("pmds", { bubbles: true, detail: pmds });
    document.dispatchEvent(event);
  }

Then, in the main JS page, you handle the event like any other. In my case, I was using the data to populate a jQuery autocomplete field:

document.addEventListener("pmds", function(event) {
  if (event.detail?.length) {
    $("#pmd").autocomplete("option", "source", event.detail);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.