Utilizing vanilla JavaScript's addEventListener in a Vue component

It appears that vanilla event listeners do not function properly when targeting DOM elements within Vue components.

Code Snippet

<p id="test1">Hover over this (works)</p>
<div id="app">
    <p id="test2">Hover over this (not working)</p>
</div>

JavaScript

document.querySelector('#test1').addEventListener('mouseover', function() {
    alert("HOVER1")
})

document.querySelector('#test2').addEventListener('mouseover', function() {
    alert("HOVER2")
})

new Vue({
    el: "#app"
})

Live Example

View live example here

Is this behavior intentional? Are there any other restrictions when mixing vanilla JavaScript with Vue?

Answer №1

It appears that the example using alert("HOVER2") is not functioning as expected due to Vue's dynamic rendering of content. When your script loads, the element you are trying to add the event listener to may not exist yet.

To make it work, consider moving your code to the mounted hook:

new Vue({
  el: "#app",
  mounted() {
    document.querySelector('#test2').addEventListener('click', function() { alert("HOVER2") })
  }
})

Alternatively, you can utilize a workaround by placing your querySelector within a setTimeout(() => ..., 0) function, which will delay its execution until all other queued tasks are completed:

setTimeout(() => document.querySelector('#test2').addEventListener('click', function() { alert("HOVER2") }), 0);

It is recommended to utilize Vue's built-in event handling system and avoid direct DOM manipulations. Vue manages its virtual DOM and updates it accordingly, so using Vue's event handlers is preferred over direct DOM manipulation to ensure consistency and prevent issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

Is it possible to turn off security features for a Heroku Postgres database?

My project doesn't involve sensitive data, so I'm not concerned about security vulnerabilities. I believe the issue lies in the connection between the App/server and the DB. I've searched on Youtube and Google for solutions, but the informa ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

Utilizing AngularJS: Binding stateParams value to custom data within state objects

Following the guidelines here, I am setting a page title in my state object. $stateProvider .state('project', { url: '/projects/:origin/:owner/:name', template: '<project></project>', data : { pageTi ...

Adjust the value based on selection

I aim to display another div when either the Full Time or Part Time option is selected. Additionally, I would like to calculate a different value for each option; if 'Part Time' is chosen, PrcA should change to PrcB. Here is the code snippet tha ...

Exploring nested JSON through recursive iteration in JavaScript

Consider this JSON data containing comments that are fetched via AJAX call: json = 'comments': [ {'id':1,'parent':0}, {'id':2,'parent':1}, {'id':3,'parent':2}, {'id&apos ...

Is it possible to retrieve AJAX data through a callback function?

I have encountered an issue where the ajax success function does not return data as expected. I attempted to use a callback function instead, but I still end up with undefined results. I resorted to using the variable responseText, however, I am looking fo ...

develop a submission form using jquery

I am looking to create a submit action where clicking the submit button does not refresh the page. Instead, the data inputted in div1 will be sent to kanjiconverter.php and displayed in div2 using <?php echo $newkanji ?>. There are three forms on thi ...

Another way to utilize slot="headerCell" in v-data-table Vuetify version 2.x

I'm currently in the process of upgrading to Vuetify 2.x from an older version. <template slot="headerCell" slot-scope="props"> <tableheader :props="props"/> (a custom component where I pass props to displ ...

RtcMulticonnection is not currently connected to any room

Trying to create a small video conference application, I developed a basic RTCMulticonnection app. However, it keeps sending repeated requests: https://rtcmulticonnection.herokuapp.com/socket.io/? userid=b1nxbxqjvhd&sessionid=mywebsite&msgEvent=RTC ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

How can cookies be managed with JavaScript, Express.js, or Node.js?

Could anyone advise on the optimal approach for managing cookies - through Express.js, Node.js, or client-side JavaScript/jQuery? I'm feeling a bit uncertain about security implications. Your assistance and insights are greatly appreciated. ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Unable to retrieve data in Vue using Axios for GET request

Recently delving into Vue, I'm struggling to figure out what's causing the issue in my code. Here's a simple component snippet: <template> <template v-if="loading"> Loading... </template> <te ...

Stop the scrolling behavior from passing from one element to the window

I am facing an issue with a modal box window that contains an iframe. Inside the iframe, there is a scrollable div element. Whenever I try to scroll the inner div of the iframe and it reaches either the top or bottom limit, the browser window itself start ...

How can I trigger an event to append a UL element using

Can anyone suggest a more elegant solution for handling an append/remove event from an element without having to manually trigger an event or resorting to other methods? It would be great if there was a way to do something like this: $('#id').o ...

Tips for adding a scroll-to-top button on a page with only a vertical scroll bar

How can I make the scroll to top/bottom button only show up on pages with a vertical scrollbar? Currently, the button is not appearing when the page contains a vertical scrollbar. Any suggestions on how to implement this feature? ScrollToTopBottom.vue < ...

Tips for troubleshooting aspx pages following an ajax post back?

I am currently working on a project with a unique architecture. During the page_load event, we utilize a switch case structure: switch (command) { case "LOAD": load(); break; case "UNLOAD": ...