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

Error message occurs when trying to undo the Union operation in ArcGIS 10.2, resulting in an undefined or null reference error

I am currently working on incorporating a polygon union functionality using ArcGIS 10.2 JavaScript 3.6 API with undo and redo capabilities. The union operation works fine, but I encounter an error when attempting to undo the operation: An unhandled except ...

Include a script tag in a React component in NextJS without relying on props or context

Currently, I am trying to include a library in my React component using a script tag. My approach involves calling an API in an _app.tsx file and then accessing the result in a _document.tsx file. In the _document.tsx file, I add the script tag to the docu ...

Tips on removing previously selected files from a Bootstrap 4 input file

I am currently facing an issue with a form that includes an input file implemented using Bootstrap 4. The functionality of this input file depends on Javascript: when the user clicks on the "browse files" button, a window opens for file selection, and upon ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...

When importing data from a jQuery AJAX load, the system inadvertently generates duplicate div tags

Currently, I am utilizing a script that fetches data from another page and imports it into the current page by using the .load() ajax function. Here is the important line of code: $('#content').load(toLoad,'',showNewContent()) The issu ...

Can you explain the significance of the symbol '#' in a Vue Router URL?

I am wondering about the significance of the hash in Vue Router URL. I have noticed that by using mode: 'history', I can eliminate it from the URL. What are the practical differences between having the hash and not having it? ...

"Exploring the concept of Undefined in Javascript Arrays

I keep encountering the issue links[i] is undefined. Even after explicitly defining it, the error persists. Any thoughts on why this might be happening? I am attempting to implement unobtrusive image rollovers for 5 links that I currently have. function ...

Stop the button event from triggering

Although Sharepoint is available, I believe this question pertains more to javascript and cross browsing than Sharepoint. In my Sharepoint environment, I have a custom ribbon button that should trigger a workflow for a specific element in my library. I wo ...

Conceal and reveal text with a simple user click

Currently, I am working on a website project that utilizes bootstrap. However, I am facing some uncertainty regarding how to effectively hide and display text: <nav class="navbar navbar-light" style="background-color: #e3f2fd;"> ...

Tips for including data labels in a scatter plot using d3.js

I am currently studying d3.js for data visualization and I have chosen to work with the titanic dataset My objective is to incorporate passenger names into my visualization so that when a cursor hovers over a point, the person's name is displayed. H ...

What is the best way to find the vertex positions of a JSON model in

Here is the code I am using to load a 3D model in THREE.js: var noisenormalmap = THREE.ImageUtils.loadTexture( "obj/jgd/noisenormalmap.png" ); noisenormalmap.wrapS = THREE.RepeatWrapping; noisenormalmap.wrapT = THREE.RepeatWrapping; noisenormalmap.repeat. ...

Guide on creating a cookie in express following a successful API call

Throughout my entire application, I utilize the /api route to conceal the actual API URL and proxy it in express using the following code: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url // This ret ...

Chrome Extension: Sending Data from Panel Window to Popup - A Step-by-Step Guide

I've been developing a Chrome extension that displays a window (popup.html) containing a button for playing videos when the extension icon is clicked. Upon clicking the play button, another window created using window.create of type panel opens up. Th ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

Challenges arise with the height settings of ui-grid

Currently, I am facing an issue with using height: auto on an angularJS ui-grid. The problem arises from an inline style that specifies a fixed height on the div to which the ui-grid attribute is added. Additionally, the function getViewPortStyle() dynamic ...

What is the process for displaying a PHP array in HTML5 audio and video players?

I am currently working with two PHP arrays. The first array, array "a," contains strings that represent paths for MP3 files on the server. The second array, array "b," contains strings representing paths for MP4 files. For example: $test = 'a.mp3&ap ...

What is the correct way to iterate through an object, evaluate three properties, and then push them into an array?

I am tasked with creating a function called runOnRange that will populate a new array based on the properties of an object. The object contains three properties: start, end, and step. The goal is to push specific numbers into the array according to these p ...

What is the best way to update parent data from a child component?

Upon further investigation, it appears that updating data from child to parent should be done by emitting events rather than using v-model. Here is my attempt at implementing this method (unsuccessfully). App.vue <template> <div> <Hel ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...

React is unable to identify the `isDisabled` attribute on a DOM element within an img tag

After updating my React/Next.js App, I encountered the following issue: Upon investigation, React is indicating that the isDisabled prop is not recognized on a DOM element. To resolve this, you can either specify it as lowercase isdisabled if you want it ...