Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

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

Answer №1

Check out the sandbox for a demonstration.

You can access the addEventListener function on the parent's subTree.el.

For example:

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

Here's how you can implement it:

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));
},

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

Unexpected behavior of ion-select: No rendering of selected value when applied to filtered data

I came across an unexpected issue with the dynamic data filtering feature of ion-select. In my application, users are required to choose three unique security questions during registration. I have an array of available questions: questions: Array<{isSe ...

Changing URLs dynamically in NuxtJS

I am looking to replicate the functionality of WordPress using Nuxt. Within my page folder, I have organized my structure as follows: index.vue -tools --_id.vue --index.vue -material --_id.vue --index.vue With Nuxt, routes will be generated accordingly; ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

Having trouble sending an array with res.send() in NodeJS

My User model contains a field that stores an array of course IDs like this: "courseId" : [ "5ac1fe64cfdda22c9c27f264", "5ac207d5794f2910a04cc9fa", "5ac207d5794f2910a04cc9fa" ] Here is how my routes are set up: router.get('/:userid/vendo ...

Using a for loop in conjunction with Observable.forkJoin

In my component, I am striving to populate an array known as processes, containing individual process objects that each have a list of tasks. Currently, I am dealing with two API calls: /processes and /process/{processId}/tasks I utilize the /processes ...

Tips for creating a condensed header

As a newcomer to HTML, I am facing challenges in creating a simple header similar to the one displayed on this website or the example in the image below. Below is the snippet of HTML that I have attempted: <header class="header"> <div ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Transclusion with multiple slots in AngularJS

Attempting to incorporate a component in AngularJS 1.5.8 with multi-slot transclusion. The test performs well when utilizing a directive, however, with a component, it appears that the slot cannot be located!. This is how the component is declared app. ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

What is the process for dynamically altering the source file of VueRouter?

Hello, I am working on a project that involves multiple roles using VueJs and Laravel. Laravel is used as the back-end while Vuejs serves as the front-end. The project has three different roles: User, Modirator, and Editor. Here is a snippet of my code ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

Adding the Authorization header in an Ajax request within ExtJS can be easily done by including the

I've been struggling to upload a file using ExtJS and web API. The issue I'm facing is that when trying to send an authorization header to the server, it always returns as null. I even attempted to include the header in the XHR request within the ...

Is there a way to deactivate middleware in Node, Express, and Mocha?

My application features a hello world app structured as follows: let clientAuthMiddleware = () => (req, res, next) => { if (!req.client.authorized) { return res.status(401).send('Invalid client certificate authentication.'); } ret ...

AngularJS $scope changes not reflecting in the view

Struggling with a persistent issue in my angularJS $scope. I've been working on updating an array within a controller function, and even though the values are changing based on console logs, the view isn't reflecting those changes. Here's wh ...

The Angular directive is failing to refresh the data on the Google Map

I created a directive called "myMap" to incorporate a Google map into my application. However, I am facing an issue when attempting to update the longitude and latitude values for a different location using a controller function. The directive does not ref ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

Is it possible to automatically adjust the cursor position in a textarea when the language is switched?

I am working with a textarea that needs to support both English and Arabic languages. In English, text is typically left-aligned, so the cursor should start on the left-hand side. However, in Arabic, text is right-aligned, meaning the cursor should begin ...