How can I attach an addEventListener
to the parent element in Vue 3.x?
I discovered that you can access the parent by using this code:
import { getCurrentInstance, onMounted } from 'vue'
onMounted(() => {
console.log(getCurrentInstance().parent)
})
But how do I locate the HTML
element so that I can set up the listener on it?
I am currently in the process of transitioning my code from Vue 2.x to Vue 3.x.
In Vue 2.x, you could easily add an EventListener to a specific element like this:
mounted() {
this.$el.addEventListener('scroll', throttle(this.handleScroll, 50));
},
beforeDestroy() {
this.$el.removeEventListener('scroll', throttle(this.handleScroll, 15));
},
Crucial point: I do not want to apply the listener to the window
or document
elements of the browser.
My aim is to track the scroll behavior of a particular element. The overall scroll state of the browser may remain unchanged. Refer to this image for clarification:
https://i.stack.imgur.com/2y7gsm.png
As illustrated, scrolling is limited to the div-box containing the placeholder text.
Now onto my dilemma:
I am utilizing swiper.js
to create multiple slides positioned adjacently.
The structure of the code resembles this:
<SwiperWrapper>
<SwiperSlide>
<FirstSlide />
</SwiperSlide>
<SwiperSlide>
<SecondSlide />
</SwiperSlide>
<SwiperSlide>
<ThirdSlide />
</SwiperSlide>
</SwiperWrapper>
<SwiperSlide>
represents the element where I wish to include an EventListener for scroll events as it's the sole div
with a scrollbar due to overflow-y: auto;
.
Since <SwiperSlide>
is a component from swiper.js
, I need to add the EventListener within every slide element (e.g. <FirstSlide>
, <SecondSlide>
etc.)
To grasp my issue better, here's an example showcasing how I tackled it previously if you check out the script below.
https://codesandbox.io/s/swiper-navigation-vue-forked-vem09w?file=/src/FirstSlide.vue