How can I place a button inside a router link and ensure that only the button is triggered when clicked, rather than both the button and the link?

Let me explain the situation: I have a router link embedded within a navbar, and on top of that there is a button that triggers a route change.

Here is the relevant code snippet:

<router-link v-if="foo" :to="/">
...
  <button @click="redirect"> GO </button>
...

The method used for redirection:

redirect() { this.$router.push('/myroute').catch(() => {})

I attempted to manipulate the z-index of both elements, but when I click on the GO button, it first navigates to '/myroute' before going back to '/'.

Is there any workaround for this issue?

Answer №1

If we utilize event.stopPropagation(), we can effectively halt the propagation of the current event during the bubbling phase. This means that the event will only be stopped at the button element.

navigate(e) {
    e.stopPropagation();
    this.$router.push('/desiredpath').catch(() => {});
}

Answer №2

To prevent event propagation in Vue, you can utilize the stop modifier with the @click directive.

<router-link v-if="foo" :to="/">
...
  <button @click.stop="redirect"> GO </button>
...

In Vue, using stop is similar to calling stopPropagation on an event.

The z-index attribute affects the button's display. Events bubble up from inner DOM elements to their containing nodes. If there are no other event listeners attached, the click will behave as expected.

Alternatively, you can place the button and router-link as siblings within an outer <div></div>, applying flex styling to position them accordingly.

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

Clients using Socket.io are known to establish connections with various sockets housed within the same server

Hello, I am currently managing a standard chatroom using socket.io but have encountered an issue that I am struggling to troubleshoot. The chatroom appears to be operating normally as clients can send and receive messages. However, there is an occasional ...

What is the best way to dynamically insert components into a grid?

I have structured a grid using the v-for directive. I am looking to insert different components into each column that I've created, one component in each separate column. Although I have set up a script named view where I store the components, I am fa ...

A Guide to Displaying Django Forms.TimeField in 12-hour Format on a Template

I am facing an issue with my Django form when creating and updating model data. Upon creation, I simply input 6:30 pm using the timepicker, which works fine. However, when editing an existing record, Django displays the initial time in 24-hour format (e.g. ...

Create an HTML table with a line separating two table cells

I need help with creating a table row and td's dynamically using basic HTML and CSS. I would like to draw lines between the td's similar to the example image shown below. Can someone please assist me in achieving this? https://i.sstatic.net/GPd ...

Leveraging D3 for converting NZTM2000 coordinates to WGS84

I've been having some difficulties converting NZTM2000, a variant of the Transverse Mercator projection used in New Zealand (), to WSG84 latitude/longitude coordinates. The specifications for NZTM2000 state that the TM is set up with the following pa ...

What could be causing the shadowbox not to display in Internet Explorer?

I am currently working on fixing a shadowbox issue in Internet Explorer. The page where the shadowbox is located can be found at this link: Here is the HTML code: <div class="hero-image"> <a href="m/abc-gardening-australia-caroli ...

What is the best way to seamlessly incorporate a new line into the string saved in the AMP state?

I am exploring the world of Accelerated Mobile Pages and trying to enhance my skills. My current challenge involves adding a new line and some additional text content to a string stored in the amp-state when the user clicks a button. Here is what I have at ...

Encountering an issue when trying to submit a post request: "Received an API resolution without a response for /api/comments, which could lead to delayed requests."

Hey, I recently started diving into Next.js and I'm facing an issue with making a POST request to the API. In my project structure, I have a comments folder nested inside the api folder. Within the comments folder, I've written the following cod ...

Creating a dropdown menu utilizing JavaScript/jQuery arrays

Looking to create an HTML select menu using a JavaScript array where the keys are used as values for options. The challenge is when entering numbers as keys, they should be accepted in the code. a([selected="No of rooms", 1="1", 2="2", 3="3", 4="4", 5="5" ...

Make TR element vanish when an Ajax call is made

I have implemented bootbox to generate a modal window with the following code: $("a.delete").on("click", function() { var id = $(this).attr('id').replace('item_', ''); var parent = $(this).parent().parent(); var t ...

"ng-show does not respond to the completion of $http.success() or .error() function calls

Upon submitting a form to a web service, the following angular http post result is expected to trigger either the success or failure display of two HTML elements. Despite receiving a 200 OK response and a "Success" string in return, the success HTML elemen ...

Creating an array of objects through checkbox validation in AngularJS

$scope.data = [{ 'id': '1', 'itemName': 'mousepad', 'price': '20' }, { 'id': '2', 'itemName': &apo ...

Prevented a frame from "https://googleads.g.doubleclick.net" from accessing another frame

After placing ads on my website, they are displaying properly. However, I am receiving an error repeatedly in the console when the page loads: A frame from origin "" is being blocked from accessing a frame with origin "". The requesting frame has an "ht ...

rearranging the sequence of buttons using JavaScript

I am faced with the challenge of making a series of buttons draggable and droppable within a parent div without using any external libraries at the request of the client. Although I could have easily accomplished this task with jQuery, it's an opportu ...

Is there a way to retrieve the current day and time, including AM or PM, from the computer using jQuery?

Can someone help me display the current day and time (HH:MM) with AM/PM on my webpage using jQuery? I have already achieved this using JavaScript, but I am specifically looking for an easier way to do it in jQuery. Any guidance would be appreciated. ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

Securing nested routes in NextJs with authentication

Is there a way to authenticate all nested routes in my project? Some routes require authentication, while others can be accessed without it. For example: /admin => requires authentication /admin/posts => requires authentication /admin/posts/1 = ...

Generating a client-side MD5 hash for an image file in order to compare it to the hash calculated by Firebase?

Is there a way to calculate the MD5 of an image file on the client side within my Angular Map application, that will match the MD5 when I store the file on Firestore? I need to verify that a user's file matches a reference version stored in Firebase ...

What is the best way to extract a message as an object from a JSON data in discord.js?

Currently in the process of developing a discord bot with an election feature for my server's moderator. All the necessary election data is being saved in an external JSON file to ensure that if the bot crashes during an election, it can seamlessly re ...

What is the best way to store tests away from the source directory in Vite projects?

Executing npm init vue@latest using the specified setup https://i.stack.imgur.com/2c7XX.png results in a Vitest spec file being created in the src directory. I am curious as to why Cypress e2e tests are placed in a separate directory while Vitest unit te ...