Reputation: 2053
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?
Upvotes: 2
Views: 1172
Reputation: 2053
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);
}
Upvotes: 3