Remove an item using a function embedded within it

I've been grappling with this issue for quite some time now and I'm unable to find a solution. My approach involves Vue(JS).

What I'm attempting to achieve is to push notifications into an Object and then present them to the user. Each notification has its own functionality when clicked, but I'm having trouble implementing the delete feature.

I am leveraging Vue's reactive properties for this task.

I have extensively researched how to delete an object using its own function, but I haven't had any success so far.

The reason I refrain from using @click to delete the object as well is because I want to ensure that the action within the notification is executed before deletion.

I have created a simplified JSFiddle: https://jsfiddle.net/eywraw8t/319133/

new Vue({
  el: "#app",
  data: {
    notifications: [
      { 
      text: "Some notification", 
      action: function() {
      alert("Something 1");
          // Once done, delete this particular notification entirely
        }
      },
      { 
      text: "Another notification", 
      action: function() {
      alert("Something 2");
          // Same as above
        }
      }
    ]
  }
})
.notification {
  background-color: #bbb;
  margin: 5px;
  cursor: pointer;
  padding: 15px;
  border-radius: 3px;
  box-shadow: 2px 2px 3px rgba(0,0,0,.2);
  
  width: 200px;
  transition: .1s ease;
}

.notification:hover {
  background-color: #ccc;
}

body {
  font-family: 'Roboto';
  background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  (Click on one)
  
  <div class="notification" v-for="notif in notifications" @click="notif.action">{{ notif.text }}</div>
  
</div>

Any assistance you can provide would be greatly appreciated. Thank you in advance.

Answer №1

If you want to achieve it in a similar way, you can check out this example.

When utilizing v-for and manipulating the displayed array, it is recommended to include the key attribute (the id can be autogenerated). This helps Vue accurately render the items.

new Vue({
  el: "#app",
  data: {
    notifications: [
      { 
      id: 0,
      text: "Some notification", 
      action: function() {
        return confirm("Something 1");
          // Remove this object completely to dismiss the notification
        }
      },
      { 
      id: 1,
      text: "Another notification", 
      action: function() {
          return confirm("Something 2");
          // Same as above
        }
      }
    ]
  },
  methods: {
  processNotif(index) {
       const notif = this.notifications[index];
       const result = notif.action();
       if (result) this.notifications.splice(index, 1);
    },
  }
})
.notification {
  background-color: #bbb;
  margin: 5px;
  cursor: pointer;
  padding: 15px;
  border-radius: 3px;
  box-shadow: 2px 2px 3px rgba(0,0,0,.2);
  
  width: 200px;
  transition: .1s ease;
}

.notification:hover {
  background-color: #ccc;
}

body {
  font-family: 'Roboto';
  background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  (Click on one)
  
  <div :key="notif.id" class="notification" v-for="(notif, index) in notifications" @click="processNotif(index)">{{ notif.text }}</div>
  
</div>

Answer №2

To remove an item from the notifications array, you can utilize standard array manipulation techniques:

array

notifications: [
      { 
      text: "Notification A", 
      action: function() {
            // do something
        }
      },{ 
      text: "Notification B", 
      action: function() {
            // do something
        }
      }
]

Deleting an object from an array

let index = 1
notifications = notifications.slice(index)

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

When accessing req.user in code not within a router's get or post method

Is there a way for me to access the data in the User schema outside of a post or get request? I am asking this because I would like to use this information elsewhere. The user schema is defined as follows: const mongoose = require('mongoose'); c ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

Passing an empty JSON object through Ajax requests

To Whom it May Concern (I am simply attempting to meet the "please add more detail" requirement) Upon sending data to the server as shown below, the body appears empty. Server // Route for POST method app.post('/pass', function (req, res) { ...

Customize variable values on-the-fly in Laravel

I am trying to create a navbar in Laravel with Vue.js as a blade.php file. I want to include a variable like {{xyz}} in the navbar, and when I navigate to another page, be able to set text using Vue.js or something similar. Can someone assist me with this? ...

Subdomain for an Ajax request

Can we use ajax requests to extract data from and fetch information from pages like ? It appears that JavaScript still does not permit subdomain requests. ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

A comprehensive guide on troubleshooting the toggleComplete functionality for React Todo applications

When you click on an item in the to-do list, it should show a strikethrough to indicate completion. However, when I try clicking on an item, nothing happens. Here is my toggleComplete function and where I am attempting to implement it: class ToDoForm exten ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Unable to figure out why information is not being transferred to an array through Mongoose

Seeking assistance as I am unable to figure out how to place a set of information into an array named "teamDetails". Here is the relevant /post item from server.js: app.post('/create', (req, res) => { console.log('Post command receiv ...

Tips for managing React state when dealing with multiple axios callbacks that modify an array's state

I am currently working on a React component that allows users to upload images. In this scenario, I aim to upload 3 images. After each file is uploaded, I want to append it to the list of uploaded files. Issue: The setter method in useState is asynchronou ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

I am unable to retrieve the information for the object in a JSON format

I have a JSON file containing an object { "id": 387, "name": "flatFive", "coordinates": { "x": 9.6, "y": 2.2 }, "creationDate": { "year": 2020, "monthValue": 4, "month": "APRIL", "dayOfMonth": 1, "dayOfYear": 92, "dayOfWeek": "WEDNESDAY", ...

In JavaScript, the input box is set to automatically capitalize the first letter, but users have the ability

How can I automatically capitalize the first letter of a user's name input, but allow for overrides like in the case of names such as "de Salis"? I've read on Stack Overflow that CSS alone cannot achieve this with text-transform:capitalize;, so ...

Tips for effectively handling numerous events from multiple Slickgrid instances on a single page

I'm encountering an issue with utilizing multiple Slickgrids on a single page. With the number of grids changing dynamically, I generate them within a JavaScript function and maintain them in a grid array as shown below. var columns = []; var options ...

Error: Unable to access the applicant's ID as it is undefined

I'm currently facing an issue with passing parameters from server.js to humanresources.js in a login request. Although the params are successfully printed out in server.js, they appear as "undefined" once passed on to the function in human resources.j ...

Explore Silverlights assortment using JavaScript

I have embedded a Silverlight class into my page, and in App.xaml.cs this component is registered to allow calls to Silverlight methods from JavaScript, which is functioning correctly. However, I now want to access not just methods, but collections. For e ...