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

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

Is it possible to use JavaScript to retrieve a client's bookmarks with their consent?

Is there a way to streamline the process of importing bookmarks to my server for users? Can I use JavaScript to automatically retrieve a user's bookmarks, or is that not possible due to security concerns in browsers? ...

Instead of relying on traditional AJAX for receiving remote commands, consider using a new Image object in your code like this: `var

How efficient is the following method: var i = new Image(); i.src = 'http://secondary.domain.com/command.gif?command=somecmd&rand=' + ...epoch time....; ... utilizing mod_rewrite to redirect the above URL to a PHP script ... Is this an effe ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

Modify the text of a button using JavaScript without referencing a specific div class

THE ISSUE I'm facing a challenge in changing the text of a button on my website. The <div> I need to target doesn't have a specific class, making it difficult for me to make this edit. While I have some basic understanding of JavaScript, ...

A step-by-step guide on how to fetch data by id using Vue.js and Laravel

One of my challenges involves managing a database table named candidate_profiles which consists of various columns such as 'user_id', 'photo_id', 'resume_id', 'video_one_id', 'video_two_id', 'video_thr ...

React redux - unable to load store without encountering any errors

I am currently working on a project inspired by the code example in the Learning React book, which focuses on using react redux and react router for a single page application. You can find my project here, where I have tried to replicate the example. To r ...

Troubleshooting problem with AngularJS ng-repeat

Seeking assistance with an angularjs issue as a newcomer to the platform. Building a photo gallery where the initial page displays thumbnail photos from twitter and instagram using ng-repeat loop. Hovering over an image fades it out, revealing a button f ...

Redis: Unable to establish a connection as net.connect is not recognized as a

I'm struggling to integrate Redis with nodejs Encountering issues during execution Despite using the same code, I am facing this error: Here's my code snippet: import { createClient } from 'redis' export const client = createClient({ ...

Why is the leading zero being ignored when I try to print the contents of the session in PHP?

Encountering an issue with printing the content session. The problem arises when creating the session, as the variable is initially in string format (varchar obtained from a mysql field): Initial variable: 09680040 Printed with alert or displayed in div: ...

Guide to installing angular-ui-bootstrap through npm in angularjs application

My goal is to incorporate angular-ui-bootstrap into my project using the following steps: 1. npm install angular-ui-bootstrap 2. import uiBootstrap from 'angular-ui-bootstrap'; 3. angular.module('app', [      uiBootstrap    ]) I ...

Strategies for simplifying this extensive if/else block

My current if/else statement in React Native is functional but seems verbose. I am curious to know how other developers would optimize and shorten it. I feel like my code represents a beginner's approach, and I welcome suggestions on how to improve i ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...

When transferring JSON to JavaScript within Laravel, the JSON data gets converted into HTML entities by JavaScript

Within my Laravel controller, I am constructing a multidimensional associative array: $trendChart = Array ( "series" => Array ( "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5) ), "xaxis" => Arr ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

Unlocking fashion with $refs: A step-by-step guide

After using console.log(this.$refs['block' + row + column]);, I confirmed that I can successfully access the HTML element it refers to. https://i.stack.imgur.com/7KYqB.png However, when attempting to access the element's style using variou ...

The v-for directive is causing issues with loading the array

Currently, I am attempting to iterate through a group of users sourced from the jsonplaceholder API. Below is the code for my Vue component: new Vue({ el: "#vue-app", data: { name: "dani", thumbnail: '', users: [] }, beforeM ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...