Home > Enterprise >  Vue 3 Typescript Add event listener to html element that has an id only (do not have access to the e
Vue 3 Typescript Add event listener to html element that has an id only (do not have access to the e

Time:09-07

I am using a gantt chart, Vue 3 component, that is a module I imported, so I have no access to the underlying html. I am able to see the ids and classes that are used via the the Chrome inspector, but no way to add a ref property or add events (since I don't have access to the html for each element). I used CSS to add a scroll bar to one of the ids, but also need to add an event listener to the element with that specific id. How can I do this in Vue 3 with Typescript? The reason I need to add an event listener is so I can scroll two scroll areas at the same time. I already have the scroll event on my component and need to be able to access the scroll event of the external module html element, as well.

CodePudding user response:

Short answer: it looks like you can't.

Please read this and choose one of the available events. From the docs you've mentioned I can see the following events:

mousedown-bar
mouseup-bar
dblclick-bar
mouseenter-bar
mouseleave-bar
dragstart-bar
drag-bar
dragend-bar
contextmenu-bar

Also note that how don't need to access a component inner's HTML to understand where to bind events but you can't force events in components that don't emit such events.

CodePudding user response:

Remember that, the Vuejs app is just a normal web app so you can do anything with Javascript. So I recommend you to have solid Javascript knowledge along with Vuejs.

To answer your question, you can just get your element by ID and attach any event to it:

const yourElement = document.getElementById('your-element-id')
// make sure the element is exists first
if (yourElement) {
  yourElement.addEventListener('click', () => {
    // Do something
  })
}

But you need to guarantee two points to make it work:

  • The element has to be exists before you access it
  • The ID is the same at anytime

To ensure the first point you should access your element after rendering the chart. A nextTick or setTimeout should be useful here.

For the second point, it depends on the library you are using.

  • Related