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

Deactivate the rest of the buttons by utilizing the e.target.id

I have ten expansion panels. When I click a button in one expansion panel, I want to disable other buttons in the remaining expansion panels. The issue is that when I try to target an id, it does not return e.target.id but instead returns as the value pass ...

Angular JS element cannot be located

My Angular object is not being passed when I write a new function, and I'm unsure why. The object, named person, is directly bound in the HTML and returns 2 items from the cardsCollection array. The function I'm attempting to create is called cl ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

getting a null response when using the map feature - coding battles

Given an array filled with integers, my goal is to generate a new array containing the averages of each integer and its following number. I attempted to achieve this using the map function. var arr = [1,2,3,4]; arr.map(function(a, b){ return (a + b / ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Using *ngFor to iterate through a nested collection in an Angular 2 application

I'm currently working on a challenge involving drilling down to iterate over an array within another collection of arrays within an Angular 2 application. To start off, I have set up my component to subscribe to an observable in the ngOnInit lifecycle ...

Plugin for saving inline edits in CKEditor 4

After creating a plugin for ajax save, I found the documentation confusing when it comes to implementation. How can I make the button responsive and able to save content using AJAX with PHP? Currently, I am unable to retrieve the content. Directory: /plug ...

The onKeyUp event is not functioning as expected in React, unlike the onChange event

For a React coding challenge, I am required to update a value onKeyUp instead of onChange. However, after changing it to onKeyUp, my fields are not updating and I cannot type anything into the textarea. class MarkdownApp extends React.Component { constr ...

Tips to prevent the webpage from scrolling to the top when clicking on an anchor with an ID

I have developed a CSS/HTML carousel that consists of 4 slides. The goal is to display the selected slide when clicking on the bottom button (a href). However, I am facing an issue where every time I click on a link, the selected slide appears as intended ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

What could be triggering the warning message: '[Vue warn]: data functions are expected to return an object:'

Attempting to log in and authenticate to an admin dashboard is proving to be a bit tricky for me. Upon clicking Login, I receive the token as expected, but then I notice a warning message on the console: [Vue warn]: data functions should return an object: ...

Are there any npm modules available that can efficiently transform unstructured information into a CSV format?

In my Javascript project, I am trying to export data into a CSV file. However, I am facing an issue as the data I have may contain different headers for each row. For example, the data structure could be like this: [ { name: 'John', color: &apo ...

Unable to open Vue.js and Vuetify.js Accordion

Incorporating a custom component called blog, I utilized an accordion feature from vuetify.js to display blog posts within the component using another custom component, blog-post. Initially, everything worked smoothly without nesting the components togethe ...

How to display an HTML element conditionally with v-if based on a variable's value

Looking for a way to display a <div> element, including nested <div>s, based on the value of a variable. I'm currently using v-if, but open to better suggestions. I attempted wrapping the entire <div> in a <template v-if> as s ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

D3 group of legendary elements

Is there a way to group both the circle and text elements for each legend item together? I'm currently facing a challenge with the enter/exit methods. While I can create the groups (g), I'm unable to append the text and circle elements. li.sel ...

Automating testing with WebdriverIO in scenarios where JavaScript is turned off

Is it possible to launch the browser with JavaScript disabled in the WebdriverIO framework? I am looking to automate a scenario that requires JavaScript to be disabled. However, when I try to disable JavaScript manually in Chrome or Firefox and run WDIO s ...

Displaying a value in a React component using material-ui's TextField

Can anyone help me with printing the email a user enters into the textfield within the Dialog when a button is clicked? I have been struggling to achieve this due to my function's structure. Any guidance would be greatly appreciated. export default fu ...

Node.js Express API returns an error status with an empty array response in a RestFul manner

Currently, I am in the process of developing a RestFull API using Node.JS to validate if a specific license plate is registered in my database (which happens to be MySQL). The endpoint that I have set up for this task is as follows: http://localhost:3009/_ ...

Steps to retrieve a rejected object with an error stored in it in the following .then() function

Within my chain of promises, there is a specific promise that needs to log an error but pass the remaining data to the next .then() const parseQuery = (movies) => { return new Promise((resolve, reject) => { const queries = Object.keys( ...