What is the best way to send a specific id to a modal in Vue.js?

I am having an issue when trying to delete a user using a popup alert. I have a list of users, and when I click on the delete button, I want to pass the user's ID to a modal through a method, and then use that ID in the delete method called by a button in the modal. However, I keep getting an error saying Property or method "id" is not defined on the instance but referenced during render. How can I successfully retrieve the ID of the clicked user?

Table

<tr v-for="users in pending_users.data" :key="users.id">
   <td>{{users.name}}</td>
   <td>{{users.email}}</td>
   <td>{{users.mobile_no}}</td>
   <td><button class="btn btn-danger btn-sm" @click="showModal(users.id)">Delete</button></td>
</tr>
</tbody>

Modal

<div class="modal fade" id="userDeleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
             aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Delete or Decline user</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        Do you want to delete this user?
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
                        <button type="button" class="btn btn-success" @click="deleteUser(id)">Yes</button>
                    </div>
                </div>
            </div>
        </div>

Methods

<script>
     export default {
        data() {
            return {

           }
        },
        methods: {
            showModal(id) {
                $('#userDeleteModal').modal('show');
            },
            deleteUser(id) {
              axios.post('api/deleteUser', null,
             {
                params: {
                    'user_id': id,
                        }
             })
             .then(({data}) => {

                    });

            },

        },

</script>

Answer №1

If you pass the entire item/user, you just need to define it on a model so that deleteUser can access it easily.

export default {
   data() {
       return {
           editing_user: null,
           //..
       }
   },
   methods:{
       showModal(user) {
            this.editing_user = user;
            $('#userDeleteModal').modal('show');
        },
        deleteUser() { 
          axios.delete('api/user/' + this.editing_user.id, ...),
        //..
   }

In my opinion, passing the whole item/user using showModal(user) is better instead of just passing the id. You almost always want more information than just the id.

Also, consider using

axios.delete('api/user/' + editing_user.id, ...)
for deleting the user, as it makes more sense in this context.

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

Resend the octet-stream data from an external API

I'm currently facing a challenge with retransmitting data received as octet-stream from an external API in my nodejs application. My previous attempts to convert the API response into a buffer and send it using res.write(buffer(apiResponse.data)) have ...

"Functionality of public methods in JavaScript plugin seems to be malfunction

Recently, I made the decision to redevelop a jQuery plugin using vanilla JavaScript. However, I have encountered an issue with getting the public methods to function properly. Despite all other logic working correctly, the public methods are not respondi ...

Rapid routes

Currently, I am working on developing a content preprocessor using NodeJS I have come up with 3 specific methods of preprocessing: generating html producing xhtml creating xml Each method requires different middleware, making them distinct from one anot ...

Best practice in AngularJS: Conceal/unveil fresh DOM elements or compile

Just starting out with AngularJS and looking to adjust button behavior on the fly. Coming from a JQuery background, I'm used to using element.attr('ng-click', 'controller.function()'). However, it seems that AngularJS requires co ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

What is the process for uploading files with just node.js?

My dilemma involves a webpage featuring a form with a file input field. Upon submitting the form, I wish for the server to write the file on the server side. Despite numerous attempts to upload various test images using this form, each results in a plain ...

Obtain Data Grid from Website

I need to extract a table with the following columns: "Date|Open|High|Low|Close|No.of Shares|No.of trades|Total Turnover|Deliverable Qty" from the website "" Below is the code I am using: Sub Macro_BSE() Application.ScreenUpdating = False Dim File ...

Javascript is experiencing a decrease in the variability of its content

I currently have multiple pages structured like this: <body> <table><tr><td align="center" width="100%"> --PAGE HTML-- </td></tr></table> </body> For a temporary period, I need to change the str ...

Resolving issues with a countdown timer coming to a halt

After creating a countdown timer to show 45 seconds on the screen, I attempted to control it using two buttons with JavaScript's onclick function. One button is meant to start the timer while the other stops it. While I was successful in starting the ...

CSS Grid expands the item width on its own when there is still space left

Having some queries regarding the piece of code provided. Currently, I have a collection of 5 cards displayed in rows of 3 cards each using the styling grid-template-columns: repeat(3, minmax(200px, 1fr));. My concern is whether there is a way for the 4th ...

Troubleshooting the "Write after end" issue when using Express, csvtojson, and node-walk libraries

I am encountering a problem while trying to send JSON data from csv files using Express. The process involves taking a folder of CSV files, converting them to JSON, and then outputting the result. However, I keep receiving the following error messages: Err ...

Which file should I include: npm-shrinkwrap.json, package-lock.json, or yarn.lock?

When shipping a package that is compiled only using tsc (the typescript compiler), I anticipate that consumers will install the necessary dependencies when they use npm or yarn to install my package. I aim to offer flexibility by not enforcing the use of ...

Why does the code work in two different forEach functions when it doesn't work in just one forEach function?

Within my code, I am working with an array named 'filteredTasks'. For each task in this array, my goal is to generate a button inside a Div and assign an onclick function to that specific button. Initially, I attempted to achieve this by using a ...

Creating a dynamic background image for the ul/li div element

As a newcomer to website development, I am currently exploring how to dynamically set images in the ul/li elements within a div. Below is a snippet of the HTML code I have been working on: <div class="results"> <ul class="row"> < ...

Is there a way to navigate to a specific div when clicking on it?

Need help with scrolling after running code function scrollFunction() { document.getElementById('insert').scrollIntoView(); } I have a button that triggers some code and I want the page to scroll afterwards. Currently, it scroll ...

Deleting a document in Mongo with the use of an object as a value

Hello, I'm struggling with deleting a document from my MongoDb using an object. Let me explain: const removeDocument = function (db, callback) { // Access the collection of documents const collection = db.collection(documentName) // Delete the ...

How is it that the identical group is unable to produce an accurate line chart and its corresponding range chart?

Check out my code snippet on JSFiddle here: https://jsfiddle.net/8yf7j3k6/11/ I am currently working on replicating a similar visualization of my data for a range chart, allowing me to scrub through the chart while utilizing tooltips in the line chart rep ...

What is the process for invoking a function within a dependency module?

Currently, I am diving into the world of Angular and have encountered an issue. How can I successfully call a method from a dependency module in Angular? app.js (function(){ var myApp = angular.module('myApp',['map']); myApp.f ...

How Mongoose maximizes efficiency with lean usage, populate, and nested queries

In the process of developing an app with Node.js and MongoDB, I have opted to utilize MongooseJS for handling my DB queries. There are two collections in play - Room, which serves as the main collection, and DeviceGroups, nested within the Room collection ...

Step-by-step guide on making a table of objects using JavaScript

As a new React user venturing into website creation, our goal is to design a table where each row outlines various details about an object. We aim to achieve rows similar to the example provided here. In my view, our strategy should involve generating a l ...