What are some ways to utilize v-on="$listeners" besides just for @click events?

My Button.vue component has a specific structure. I am utilizing v-on="$listeners" to transfer all listeners to the <a> element.

<template>
    <a
        v-bind="$attrs"
        v-on="$listeners"
        class="Button"
        href="javascript: void(0)"
        :class="{ disabled }"
        @click="onClick()"
    >
        <slot></slot>
    </a>
</template>

<script>
    export default {
        props: {
            disabled: {
                type: Boolean,
                default: false
            }
        },
        methods: {
            onClick() {
                if (!this.disabled) {
                    this.$emit('click');
                }
            }
        },
    };
</script>

However, I encountered an issue when trying to customize the behavior of the @click event by defining both v-on="$listeners" and @click="onClick()". The onClickDelete function ended up being triggered twice. Even using @click.prevent did not resolve the problem.

<Button @click="onClickDelete">Delete</Button>

I am seeking a solution to apply v-on="$listeners" to all events except for @click.

For more details, you can access the code sandbox.

Answer №1

To handle the $listeners object in a different way, you can make a duplicate of it (using spreading to create a new object) and then replace the click function:

<a v-on="{ ...$listeners, click: () => {} }">

Check out this first demonstration

Alternatively, you could set up a computed property that removes any click event handler:

export default {
  computed: {
    myListeners() {
      const { click, ...listeners } = this.$listeners // exclude `click` listener
      return listeners
    },
  },
}

You can then use this property with v-on instead of $listeners:

<a v-on="myListeners">

See how this works in action with the second demo

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

Bootstrap 5 dual carousel focus

I have implemented a combo carousel that serves as a timeline slider and displays 14 dates. Along with thumbnails, I am also using dates for navigation. To handle the large number of dates, I need to display them in separate rows, but only show one row at ...

Mastering callback functions within AngularJS animations

As I delve into AngularJS animations, I am currently working on a slide-show animation: app.animation('slide-show', function () { return { setup: function (element) { }, start: function (element, done) { e ...

"Utilizing regular expressions in JavaScript to check for multiple

I have a function that replaces HTML entities for & to avoid replacing &amp; but it still changes other entities like &, ", >, and <. How can I modify the regex in my function to exclude these specific entities? &apos; &quo ...

Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component. Here are a couple of examples: format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)' or format="'(tz, offset) location'" === &a ...

Elevate sublevel vue component

I am facing an issue with a nested and reused vue component. I am attempting to use v-show to display a part of the component (icons) when its outer parent is hovered. In order to achieve this, I am passing the parent and child index as props. However, I ...

Verify whether an option is chosen in CakePHP 3 form

I'm working on a form where users can select Types and each type has an associated color. In my TypesController, I have a function that retrieves the list of types with their IDs, names, and colors. $types = $this->Types->find('list') ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

How can I retrieve the name of the upcoming middleware function in Express.JS?

Hey there, I'm currently facing a challenge with retrieving the names of middleware functions in a specific request route. Let's consider the code snippet below as an example: const authorizeRoute = (req,res,next) => { let nextFunctionName = ...

Event triggered when a Socket.IO connection is disconnected

Everything seems to be working well with my code when a new user joins, but I'm encountering issues when a user leaves as it doesn't display anything. Can someone point out the error in my code? Below is my server-side code: const express = requ ...

What could be causing the failure of this mock jest test?

I've been working on simulating document.clipboard in my code. This is the code snippet: handleCopyIdToClipboard = () => { const el = document.querySelector(`.${CLASS_NAME}`); navigator.clipboard.writeText(el.textContent); // addit ...

The $http.get in AngularJS is causing a problem by returning undefined and $http() is not being recognized

I am currently working on an app that is designed to load and display data dynamically from a database using AngularJS. However, I have been encountering errors when trying to access my API using both $http() and $http.get(). The specific errors I am recei ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...

The complete page gets re-rendered when Nuxt child routes are used

When I attempt to utilize child routes, my goal is to maintain specific data on the page while modifying other content. To illustrate this concept, I have created a straightforward example available at this link. After selecting "cat" and increasing the ...

Partially translucent electron window

Is there a way in Electron to create a view similar to the finder in macOS, where the sidebar is opaque and the main content is not? https://i.stack.imgur.com/UKXg2.jpg I am aware of how to make an entire window opaque, but I'm unsure if it's p ...

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

Learn how to toggle the visibility of multiple divs using Vuejs and the @click directive. Perfect for those who

I'm struggling with figuring out how to toggle the visibility of 3 different divs based on a click event. Although I've managed to show and hide 2 divs using v-show, I believe v-show doesn't work for more than 2 divs. Here's my code w ...

a Vue.js directive that acts based on a specific variable

Can a directive be dynamically assigned based on a variable? I want to assign either success or error depending on the value of a variable called type. The current implementation is as follows (and I am looking for an alternative approach): v-snackbar(v ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...