Vue 3.0: How to add an addEventListener to the parent element?

Viewed 1094

I don't know how to add an addEventListener to the parent in Vue 3.x.

I found out that you can get the parent by using this code:

import { getCurrentInstance, onMounted } from 'vue'

onMounted(() => {
    console.log(getCurrentInstance().parent)
})

But how do I get the HTML-element so I can add the listener to it?


I am currently trying to migrate my code from Vue 2.x to Vue 3.x.

In Vue 2.x you could easily add an EventListener to a specific element:

mounted() {
    this.$el.addEventListener('scroll', throttle(this.handleScroll, 50));
},
beforeDestroy() {
    this.$el.removeEventListener('scroll', throttle(this.handleScroll, 15));
},

Very important: I do not want to add the listener to the window element or document element of the browser.

I want to know the scroll state of a particular element. The scroll state of the browser may not even have moved. Have a look at this picture:

enter image description here

As you can see, you can only scroll inside the div-box where you see the placeholder text.

Now to my problem:

I'm using swiper.js to generate many slides next to each other.

The structure of the code looks something like this:

<SwiperWrapper>
    <SwiperSlide> 
        <FirstSlide />
    </SwiperSlide>
    <SwiperSlide>
        <SecondSlide />
    </SwiperSlide>
    <SwiperSlide>
        <ThirdSlide />
    </SwiperSlide>
</SwiperWrapper>

<SwiperSlide> is the element where I want to have an EventListener on scroll, because this is the only div element that is scrollable due to overflow-y: auto;.

But because <SwiperSlide> is a component from swiper.js, I have to add the EventListener inside each slide element (e.g. <FirstSlide>, <SecondSlide> etc.)

Here is an example to understand my issue better. If you scroll down to script, you will see how I did it in the past.

https://codesandbox.io/s/swiper-navigation-vue-forked-vem09w?file=/src/FirstSlide.vue

1 Answers

You can try Sandbox

The addEventListener function is available on the parent's subTree.el.

Like:

const parentHTML = getCurrentInstance().parent.subTree.el
parentHTML.addEventListener('click', () => console.log('click'))

So you can do:

data: () =>({
    parent: null
}),
mounted() {
    this.parent = getCurrentInstance().parent.subTree.el;
    this.parent.addEventListener('scroll', throttle(this.handleScroll, 50));
},
beforeDestroy() {
    this.parent.removeEventListener('scroll', throttle(this.handleScroll, 15));
},
Related