How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and runs the close function even though the event has already occurred. I'm puzzled as to why this happens and how can I prevent the event from running immediately after the toggle is executed. It should only be triggered on subsequent clicks after the initial one on the <a> tag.

<template>
    <div>
        <a v-on:click="this.toggle">Account</a>
        <nav v-if="this.open">
            <a>Profile</a>
            <a>Settings</a>
            <a>Sign Out</a>
            <a>Admin</a>
        </nav>
    </div>
</template>

<script lang='ts'>
    import { Vue } from 'vue-property-decorator'

    export default Vue.extend({
        data: function () {
            return {
                open: false
            }
        },
        methods: {
            toggle: function () {
                this.open = !this.open
                if (this.open) {
                    // Add click listener to whole page to close dropdown
                    document.addEventListener('click', this.close)
                }
            },
            close: function () {
                console.log('test')
                this.open = false;
                document.removeEventListener('click', this.close)
            }
        }
    })
</script>

Answer №1

In the insightful comment by Chris G, it was pointed out that what you are experiencing is event bubbling up to the document after adding the listener. The good news is that Vue simplifies this process for you. To address this issue, you can modify your event handling code to v-on:click.stop="this.toggle"

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

Merge multiple Javascript files into one consolidated file

Organizing Files. /app /components /core /extensions - array.js - string.js /services - logger.js /lib - core.js Core.js (function() { 'use strict'; an ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

Guide to efficiently utilizing flex to horizontally position two elements next to each other in a Material UI and ReactJS environment

I have successfully achieved side-by-side components of two cards from Material-UI. However, I am facing an issue when expanding one of the cards. The problem is that Card 1 automatically expands to match the size of Card 2 when Card 2 is expanded, even th ...

Items that have been moved in the Vuetify Treeview are unable to be selected when clicking on the parent node

After successfully moving selected treeview items to another parent, I have encountered an issue where the moved items are no longer selectable when clicking on their new parent node. To reproduce this issue, follow these steps: Select node2_item1 Click ...

What is the best method for converting input files into FormData?

I recently created a form that allows users to upload both an audio file and an image file simultaneously. However, during testing, I noticed that the alert only displays basic data and does not include the form data. function PodcastUpload({ data }) { ...

How to add a design to an image using a fabric pattern on a shirt

https://i.stack.imgur.com/ocWBp.png If I have an image and want to fill it with fabric below. And the final image will look like this: https://i.stack.imgur.com/vVv0I.png I just want to fill a pattern in a shirt like shown in this demo. Is there ...

Having difficulty processing information retrieved from an ajax request in jQuery

Upon making a request to the server and converting the retrieved data into a table format, I utilize jQuery's .html() function to display it on the webpage. However, despite the data being visible on the page, I encounter issues when attempting to man ...

Utilizing query parameters as variables in rewrites with Next.js

My goal is to use Next JS to redirect requests from /home?id=123qwert to the new path of /home/123qwert. I'm struggling with extracting the query parameter from the source and using it in the destination. This is what I have attempted so far: as ...

How to customize the hover and active properties of a checked checkbox in Vue 3 using Tailwind CSS and PUG?

It seems that checkboxes have a level of sophistication that I never anticipated, or perhaps my brain just can't quite grasp the nuances of checkboxes. After spending a significant amount of time researching and experimenting with checkboxes in a Vue ...

JavaScript string manipulation function

Hey everyone, I need help finding a one-line solution in JavaScript to determine if a string contains a semicolon without using a loop. If anyone knows how to do this, please share your knowledge! ...

What could be the reason for the container div's height not being properly refreshed?

When adding elements to a container div with an initial height of 'auto', I assumed that the height would adjust based on the children elements added. However, this is not happening. Can anyone assist me in ensuring that the container div's ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Learn the process of adding asynchronous middleware modules to your express.js application

I'm currently developing an express application that utilizes the node_acl module along with a MongoDB database. I have created a custom module that sets up and configures node_acl asynchronously. This middleware needs to be called as the second piece ...

The Vue Multiselect feature lacks accessibility for screen readers when in a disabled state

My current project involves using Vue and multiselect to create a dropdown menu of countries. I have encountered an issue where the dropdown is preselected with a value and disabled. Despite this, I need the selected value to remain accessible for screen r ...

Jquery's mouseclick event selects an excessive number of elements

Is there a way to retrieve the ID of an element when it is clicked, only if it has one? I currently have this code set up to alert me with the element's ID: $("[id]").click(function(event) { event.preventDefault(); var id_name = $(this).attr ...

Encountering an error with Next.JS when using the "use client" directive

Recently encountered a bizarre issue with my next.js project. Every time I input "use client"; on a page, it triggers a "SyntaxError: Unexpected token u in JSON at position 0". Here's the code snippet for reference: "use client" ...

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...

What is the reason for the emergence of this error message: "TypeError: mkdirp is not recognized as a function"?

While running the code, I encountered an error indicating that the file creation process was not working. I am seeking assistance to resolve this issue. The code is designed to fetch data from the Naver Trend API and Naver Advertising API, calculate resul ...

Can the axios version be displayed during runtime?

I have incorporated axios into my project using npm import axios from 'axios' Is there a way to print the version of axios in the console after the entire application has been compiled? ...

Sorting information in the React Native Section List

Working with React Native's SectionList and filtering data: data: [ { title: "Asia", data: ["Taj Mahal", "Great Wall of China", "Petra"] }, { title: "South America", data: ["Machu Picchu", "Christ the Redeemer", "C ...