Clicking on a Vue.js element does not trigger the function when an <a> link is present

I am attempting to create a notification system where clicking on the notification and accessing its link will result in a decrease in the total number of notifications.

<li class="header">You have {{ notificationsCount() }} notifications</li> <li>
  <ul class="menu">
    <li v-for="(notification, index) in notif" :notification="notification" :key="notification.id">                  
      <a :href="notification.data.path"              
          @click="markAsRead(notification.id)"
          @mouseup.right="markAsRead(notification.id)"
          class="text-aqua">{{ notification.data.message }}
       </a>
      </li>
  </ul>
methods: {
        notificationsCount() {
            return this.notif.length
        },

        markAsRead(index, id) {
         if (this.notif.length){
                axios.delete(`/notifications/${id}`)
                    .then(() => {
                        this.notif.splice(index, 1);
                        this.notificationsCount();
                    }); 
            }                 
        }
    }

The issue arises when there is a specified link using `:href` as the notification count does not decrease. However, when the `:href` value is "#" or the `@click.prevent` method is used instead, the function executes successfully and the notification count decreases. How can I fix this?

Within the anchor tag, there are two triggers, `@click` and `@mouseup.right`, for handling new tab openings. When clicking with the right mouse button, the notification count decreases as expected because it executes via `@mouseup.right`. However, when executed through `@click`, the count does not decrease immediately, requiring a page reload to reflect the updated count.

Answer №1

The functionality is working as intended. The counter updates visibly before the page reloads. However, once you exit the page, the program clears out, and upon returning, it resets. To maintain data values persistently, you must utilize some form of long-term storage such as localStorage or a database. While axios is available, it cannot be implemented in this example.

If you navigate to another page via a link, the current page unloads, making it difficult to observe any changes occurring. Additionally, the identification method for splicing out an item is incorrect.

new Vue({
  el: '#app',
  data: {
    notif: [{
      id: 1,
      data: {
        path: 'http://www.google.com',
        message: 'Go to google'
      }
    }]
  },
  computed: {
    notificationsCount() {
      return this.notif.length;
    }
  },
  methods: {
    markAsRead(item) {
      const index = this.notif.indexOf(item);
      
      this.notif.splice(index, 1);          
    }
  }
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  Count: {{notificationsCount}}
  <ul class="menu">
    <li v-for="(notification, index) in notif" :key="notification.id">

      <a :href="notification.data.path" @click="markAsRead" class="text-aqua">{{ notification.data.message }}
       </a>
    </li>
  </ul>
</div>

Answer №2

The issue is that the axios request has not completed yet when the page redirects to the specified path. To solve this problem, it's recommended to refactor the redirect function so that it only executes after the axios request has successfully finished.

      ...
      <a
        @click="markAsRead(notification)"
        @mouseup.right="markAsRead(notification)"
        class="text-aqua">{{ notification.data.message }}
     </a>
     ...

     markAsRead(index, notification) {
       if (this.notif.length){
            axios.delete(`/notifications/${id}`)
                .then(() => {
                    this.notif.splice(index, 1);
                    this.notificationsCount();
                    window.location = notification.data.path
                }); 
        }                 
     }

It's unnecessary to bind both click and mouseup events together. You should choose either click or mouseup based on your specific requirements.

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

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

Refresh a Google Map by input change using Vue.js

Currently, I am facing a challenge in updating a Google Map automatically once a user inputs values into 3 specific fields: state, city, and address. Although most of my code seems to support this functionality, the use of a custom Vue directive that init ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Submit the form only when the specified conditions are met, otherwise return

Is there a way to submit a form after it has been prevented from submitting? I've searched for solutions on StackOverflow but haven't found one that works for me. Below is the code snippet in question: $(function(){ $("#loginform").submit(f ...

What are the steps to approve an Amazon Pay request for retrieving a "get checkout session"?

Exploring the integration of Amazon pay as a payment option for customers on my website has led me to encounter some challenges with understanding the request headers required for calling the Amazon Pay API. Attempting a request to 'https://pay-api.a ...

As the page is resized or zoomed in and out, the div elements start shifting in different directions

When I apply position:absolute to prevent the elements from moving when zooming in and out of the page, they all end up congregating in one place. Can anyone help me with this issue? None of the solutions I've found have worked so far. I'm develo ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

Developing an easily optimized library using rollup to remove unnecessary code branches

I'm currently in the process of developing a component library using rollup and Vue with the goal of making it tree shakable for others who import it. The configuration setup is outlined below: Here's a snippet from package.json { "name": "re ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Enhance your website with a lightbox effect using FancyBox directly in your JavaScript code

I am currently experiencing an issue with implementing fancybox on my website. I have a website that features links to articles, which open in fancybox when clicked. The problem arises when a user tries to access an article directly. In this case, the use ...

Markdown in Vue.js filters

I found a helpful example by Evan You on how to convert HTML to markdown - check it out here. However, when trying to install the marked package via npm and implementing it, I encountered an error stating that 'marked' is not defined. After inc ...

Guide on sending images as props in a Vue.js component (using Vite instead of require due to compatibility issues)

This is the main component <template> <rooms-card roomImage="../../assets/images/room3.jpg" roomType="Duplex Room" roomDescription="Sami double bed 1 guest room 3 windows" roomPrice="$50/night" /> < ...

Decode the JSON serialized format generated by CircularJSON

I have a JSON object in my node.js code that contains circular references. To send this information to the browser, I utilized the NPM package circular-json to stringify the object and serialize the circular references: var CircularJSON = require("circula ...

Waves emanating from the heart of rings

I'm experimenting with creating a ripple effect using Anime.js on an array of dots forming circles. Despite trying various methods, I can't seem to achieve the desired result. Does anyone have any suggestions on how I can make it work? Here&apos ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...

In Vue.js, I only want to retrieve and display the parent's ID or name once for each of its child components

<td v-if="currentId != loop.id" class="text-center"> <div :set="currentId = loop.id">{{ loop.id }}</div> </td> <td v-else></td> Looking to achieve a specific layout like this This invo ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

The functionality of the web application is not supported in Multi-Device-Hybrid-Apps format

I am encountering an issue with my app that functions perfectly as a typical web app, but fails to work properly when converted into a Multi-Device-Hybrid-App format. The problematic sections are indicated in a screenshot of the app. Below is my complete c ...

Using Fabric JS to update the image source of an element with a new URL

Can the src attribute of a fabric js object be changed to a CDN url? { version: '4.4.0', objects: [ { type: 'image', version: '4.4.0', originX: 'left', ... src:'www.cdn ...