Delete an element from an array after a specified timeout period

I'm currently working on a Vue component that is responsible for displaying notifications which should automatically disappear after a set time. My Alert component triggers an 'expired' event and then I handle this event in the parent component by removing the notification from the data array using splice. While this method works most of the time, there are instances where the alerts remain visible.

Vue.component('alert', {
  template: '<li><slot></slot></li>',
  mounted() {
    setTimeout(() => this.$emit('expired'), 2000)
  }
});

new Vue({
  el: '#app',
  data: {
    count: 0,
    alerts: []
  },
  methods: {
        createAlert(){
        this.alerts.push(this.count++)
      },
      removeItem(index) {
        this.alerts.splice(index, 1)
      }
  }
});

To see the issue in action, please visit this Fiddle and click the Create Alert button multiple times. You'll notice that some alerts do not dismiss as expected. Any suggestions on how to address this?

Answer №1

Instead of using index, it's recommended not to do this. Here is an alternative approach.

<div id="app">
  <button @click="createAlert">
    Create Alert
  </button>
  <alert v-for="(alert, index) in alerts" :key="alert.id" :alert="alert" @expired="removeItem(alert)">{{ alert.id }}</alert>
</div>

Vue.component('alert', {
  props: ["alert"],
  template: '<li><slot></slot></li>',
  mounted() {
    setTimeout(() => this.$emit('expired', alert), 2000)
  }
});

new Vue({
  el: '#app',
  data: {
    count: 0,
    alerts: []
  },
  methods: {
        createAlert(){
        this.alerts.push({id: this.count++})
      },
      removeItem(alert) {
        this.alerts.splice(this.alerts.indexOf(alert), 1)
      }
  }
});

Check out the revised fiddle here.

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

Sorry, but we were unable to log you in using Facebook for this app or website. There seems to be a problem with how Facebook login is set up in the NuxtJs App

I attempted to integrate firebase authentication into my NuxtJs app for Facebook social media login. Despite double-checking all settings (including hash and firebase configurations), I encountered a persistent error from Facebook. Login Failed: You are ...

Error message: Route component not valid in new Vue.js project

Working on a Vue.js project and hit an error that reads "Error: Invalid route component." Struggling to identify the root cause here. Any help in diagnosing and fixing this would be greatly appreciated. import { createRouter, createWebHistory } from &quo ...

:host background color may be missing, but the font size has been boosted?

Check out this demo where the CSS is applied to the :host element or <hello>. The font size increases but the background color remains unchanged. What do you think? styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

What is the best way to obtain the inner ID with JQuery?

How can I assign values to inside id using JQuery? Sample code from controller.cs: public GroupModel Get() { IGroupTypeRepository groupTypeRepo = new GroupTypeRepository(); IGroupRepository groupRepo = new GroupRepository(); var model = new ...

Middleware that is commonly used by both error handling and regular request-response chains

I am currently working on implementing a middleware that can set a variable in the sequence of both error and non-error scenarios. Is there a way to achieve this without disrupting the normal flow of middleware? Specifically, when I include the err param ...

Toggle visibility on the child DOM element of each item in the v-for loop

Here's an example of a template: <template> <table class="table table-hover"> <tbody> <tr> <th style="width:260px">Info</th> <th>Deta ...

Generate a dynamic file import loop within a React application

Suppose I have a directory containing several .md files: /static/blog/ example_title.md another_example.md three_examples.md and an array that includes all the titles: const blogEntries = ["example_title", "another_example", "three_examples"] In ...

Guide to combining an Angular 2 application with a Django application

Currently, I have been working through the Tour of Heroes tutorial. The structure of my Django app can be simplified as shown below: apps/my_app/migrations/ apps/my_app/__init__.py apps/my_app/urls.py apps/my_app/views.py frontend_stuff/js/ javascript ...

ChessboardJs: JavaScript Boards Function Properly on Initial Use Only

Update: The page code can be accessed via my page URL. I'm unsure where the issue lies. Your assistance is appreciated. Issue: Initially, when clicking on the chess puzzles page, everything works fine. However, upon re-clicking from the homepage, th ...

what can prevent a React component from re-rendering?

Being a novice in the realm of React, I find myself with a perplexing query. Within my application, I have two distinct components - the parent component named Goals and its child, EditGoal. The Goals component functions to display all goals, while the Edi ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Listening for key combinations in VueJS using a mounted event listener

I am facing an issue with my global key listener - it only catches single key strokes. How can I modify it to capture combinations like ctrl+enter? mounted() { window.addEventListener ( "keypress", e => { console.log ...

Transforming a namespaced function into an asynchronous operation by utilizing setTimeout

Looking for help with making a function that uses namespaces asynchronous. The function is currently being called on the click of a button. var ns = { somemfunc: function (data) { alert("hello"); } } Edit: ...

Which property is best suited for styling a phone number field in the MUI data grid in ReactJS?

I previously utilized the pattern attribute for input fields in pure HTML, but now I no longer have any input fields. What should be my next steps? Can you provide me with a reference in the MUI documentation? https://i.stack.imgur.com/ ...

Error: Browserify jQuery Plugin Not Working

Having trouble browserifying a jQuery plugin and keep seeing this error in the browsers console: Uncaught Error: Cannot find module 'jquery' Here's how I have my package.json set up: "browserify": { "transform": [ "browserify-shim" ...

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...

Conceal an element along with its space, then signal the application to show alternative content using React

Greetings everyone! I seek assistance with a React Application that I am currently developing. As a newcomer to the Javascript world, I apologize if my inquiry seems trivial. The application comprises of two main elements: a loader, implemented as a React ...

Is there a way to have a span update its color upon clicking a link?

I have 4 Spans and I'm looking to create an interactive feature where clicking a link in a span changes the color of that span. Additionally, when another link in a different span is clicked, the color of that span changes while reverting the previous ...

Generate a spreadsheet file in xlsx format by using the exceljs library in Node

I am currently working with exceljs 3.8 in an attempt to generate a new XLSX file, but unfortunately the code below seems to be malfunctioning. createNewExcelFile: function (excelFilePath) { //excelFilePath: Path and filename for the Exce ...