The Vue conditional event handling with the v-on directive and the prevent modifier

Is there a way to utilize the .prevent modifier of v-on dynamically?

<a
  href="#"
  class="modal-overlay"
  aria-label="Close"
  v-on="overlayClickClosesModal ? { click: () => closeModal() } : {}"
/>

I'm attempting to prevent the URL from appending with /#

I have experimented with

v-on.prevent

v-on:prevent

v-on="overlayClickClosesModal ? { 'click.prevent':

Answer №1

To improve clarity, consider moving the logic into a separate method:

<a href="#" @click="clickMethod">

Then, implement the check in the script section:

clickMethod (event) {
    if (this.overlayClickClosesModal) {
        event.preventDefault();
    }
}

Do you really need to add an anchor to your link? It may not be necessary and could save you some effort.


Vue does not appear to support dynamically adding modifiers: https://github.com/vuejs/vue/issues/9417

Answer №2

If you're looking for a solution, consider replacing the .prevent event modifier with a direct call to event.preventDefault() in your event handler:

<a
  href="#"
  class="modal-overlay"
  aria-label="Close"
  v-on:click="maybeCloseModal"
/>

You can define a method like maybeCloseModal in your methods section to handle this logic:

maybeCloseModal: function (event) {
  if (this.overlayClickClosesModal) {
    event.preventDefault();  
    this.closeModal();
  }
}

In your case, it might be worth considering whether clicking the link has any useful default behavior. If not, you could unconditionally prevent it by modifying the link as follows:

<a
  href="#"
  class="modal-overlay"
  aria-label="Close"
  v-on:click.prevent="overlayClickClosesModal && closeModal()"
/>

You may also want to make the aria-label attribute conditional based on the same boolean flag or use v-if to toggle between clickable and non-clickable overlays.

Answer №3

If you want to conditionally handle the same event (click), you can simplify it like this:

v-on:click.prevent="overlay ? close() : {}"

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data() {
    return {
      overlay: true
    }
  },
  methods: {
    close() {
      console.log("close")
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app" class="container">
  <a href="#" class="modal-overlay" aria-label="Close" v-on:click.prevent="overlay ? close() : {}" >close</a>
</div>

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

Is it possible to use jQuery/JS to automatically format currency input as it is typed, adding a 1000 separator and ensuring

I'm working on a text input field that needs to format the value as it is being typed, with restrictions of 2 decimal places and 1000 separators. This field should only allow for digits to be entered. Specifically, this input is meant for users to ent ...

Creating a JQuery slider that efficiently loads and displays groups of elements consecutively

Currently, I am in the process of developing an infinite horizontal tab slider using jQuery. My main objective is to optimize loading time by having the slider display only the first 10 slides upon initial page load. Subsequent slides will be loaded as the ...

What is the solution to the error message "A TypeError was encountered in the current module: e.parse is not a function"?

Can someone please help me resolve this Vue Js error I am encountering in Shopware 6 Administration? The issue pertains to selecting a column in the database table using a module. Note: Below is the complete code snippet. I am attempting to retrieve data ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

How can I acquire a duplicate of a Webgl texture?

I have a webgl texture and I have stored it in a JavaScript variable var texture1 = CreateTexture() function CreateTexture(){ var texture = gl.createTexture() // more WebGL texture creation code here return texture } I am looking to create a copy o ...

Which is the better option for data storage: JSON files or MySQL database?

I am currently developing a project that utilizes the vis.js JavaScript framework to showcase a visual network of various categories. There are approximately 2000 categories available for selection, each with a substantial amount of associated data. I am ...

Ways to allocate space evenly between components of the same size in React Native

As a beginner in Javascript and React-native, I have been experimenting with the technology to assess its viability for potential use in my current workplace. However, I have encountered some challenges with the user interface. To enhance my understanding ...

Optimal Strategies for Initializing Vuex Modules

(updated with additional context) I am facing an issue with my Vuex store module where I need it to load data automatically at the start, without any manual intervention. The particular scenario involves a 'settings' store fetching data from ele ...

How can you obtain constructor parameter from JSON directly within the constructor itself?

I decided to store the fixed parameters required for creating an object in a JSON file as an array. My goal was to have the constructor of the object fetch these parameters from the file. Although reading a JSON file is efficient, I wanted to explore othe ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

The custom classes I have created in Material UI are being overshadowed by the default classes provided by Material UI

I am trying to change the color of a TextField label to black when it is focused. I used classes in InputProps with a variable, but unfortunately, the default styling of material UI is taking precedence in chrome dev tools. Below is the code snippet. Pleas ...

Sort the data - a selection menu is included in each row of the table

My issue involves a datatable where each row must have a select item with multiple options to choose from. The goal is to filter the rows based on the selected option when using the default search bar located above the table. However, I've encountered ...

The functionality of updating the logo in the browser tabs is not functioning as expected in Vue.js 3

This is the code from my index.html: <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE ...

Enhancing Headless UI tabs with Tailwind transitions: A step-by-step guide

Can transitions be used with headlessui tabs? I am currently utilizing @headlessui/vue <template> <TabGroup> <TabList> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> < ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

Bootstrap 4: The mystery behind why the popover fails to appear inside a scrollable dropdown

Is there a way to replicate the behavior of Bootstrap 3 dropdowns with scrollbars on hover and popovers in Bootstrap 4? It seems that setting overflow:hidden; for scrolling functionality in dropdown menus also hides the popover. I have tried using containe ...

Bindings with Angular.js

I have developed an application similar to Pastebin. My goal is to allow users to paste code snippets and display them with syntax highlighting and other visual enhancements, regardless of the programming language used. To achieve this, I utilize Google&ap ...

Experienced an unexpected setback with the absence of the right-click capability on a Javascript-powered hyperlink, specialized for

I am facing an issue with a hyperlink on my website. This particular hyperlink submits a hidden form using the POST method to redirect users to another site. However, when someone right-clicks on this hyperlink and tries to open it in a new tab, they are o ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...