Executing a method in a service from a Vue.js component

A custom component was created in Vue.js 2.0 to delete items using SweetAlert. Here is the code snippet:

export default {
    props:['service', 'method', 'id'],

    methods: {
        destroy() {
            swal({
                title: 'Are you sure?',
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete',
                cancelButtonText: 'Cancel!',
                confirmButtonColor: '#34495e',
                cancelButtonColor: '#ff3860',
            }).then (() => {
                this.service[this.method](this.id)
                    .then(() => {
                        swal({
                            title: 'Deleted',
                            text: 'Successfully deleted',
                            type: 'success',
                            showConfirmButton: false,
                            timer: 2000
                        });

                        location.reload();
                    })

                    .catch(() => {
                        swal({
                            title: 'Error',
                            text: 'Do you have sufficient rights?',
                            type: 'error',
                            showConfirmButton: false,
                            timer: 2000
                        });
                    });
            })
        }
    }
}

The issue lies with the following line of code:

this.service[this.method](this.id)

I am passing the props in this manner:

<destroy :service="Service" method="destroy" :id="relation.id"></destroy>

The destroy method within the service class is as follows:

destroy(id) {
    return axios.delete('/relations/' + id);
}

In my vue debug bar, the destroy component appears like this:

https://i.sstatic.net/NSY6z.png

The error message displayed in my console is:

Uncaught (in promise) TypeError: Cannot read property 'then' of undefined
    at eval (eval at ./node_modules/babel-loader/lib/index.js?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/components/shared/Destroy.vue (app.js?id=d89bceb…:319), <anonymous>:27:54)
    at <anonymous>

Any suggestions on how to resolve this issue?

Answer №1

    const appSettings = {
        data() {
            return {
                service: null,
                method: '',
                id: ''
            }
        },
    
        methods: {
            handleDelete() {
                const vm = this;
                swal({
                    title: 'Are you sure?',
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#34495e',
                    cancelButtonColor: '#ff3860',
                }).then(() => {
                    vm.service[vm.method](vm.id)
                        .then(() => {
                            swal({
                                title: 'Deleted',
                                text: 'Successfully deleted',
                                type: 'success',
                                showConfirmButton: false,
                                timer: 2000
                            });
    
                            location.reload();
                        })
    
                        .catch(() => {
                            swal({
                                title: 'Error',
                                text: 'Do you have sufficient rights?',
                                type: 'error',
                                showConfirmButton: false,
                                timer: 2000
                            });
                        });
                })
            }
        }
    }

It is recommended to assign "this" variable to a local variable to prevent issues with the SWAL callback.

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

The array's storage is not correct

I'm dealing with this code snippet: for (let key in data ){ let info = data[ key ]; arr.push(<li>{info.name}</li>); } this.setState({ response: arr, arr: [] }) However, when I attempt the following: this.setState((prev ...

Verify if uploading a photo is necessary

Here is my approach to ensuring that a file is added before it can be uploaded: <script type="text/javascript> function check(){ var elm = document.getElementById("hello-world"); if (elm.value.length > 0){ alert("Hey"); re ...

Having trouble with passing post data from jQuery ajax to a php page?

Attempting to retrieve post data using an alert() function, but encountering an issue where the data is not being passed to the PHP page. The result always shows {"success":false,"result":0} The goal is to transmit a password to the PHP page, hash it usin ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

What is the best way to integrate Google Maps into a Vue component?

I found a helpful reference on how to retrieve the formatted address from a dragged marker in Google Maps using JavaScript in this Stack Overflow thread. Now, I am looking to implement this functionality in a Vue component. I attempted to do it like this ...

Sending an object from a web server to a client

After creating a C# web application that calls a web-service returning a base64 encoded array (PDF file), I convert the array to a UCOMIStream object to comply with the DLL parameters. The code for this conversion works flawlessly, allowing me to print the ...

What is the best way to create an arrow with text inside using HTML, CSS, and React?

https://i.sstatic.net/u5SoF.png My attempt at creating a position: relative did not work well with my adaptive site layout. I then tried making an SVG image, but it couldn't contain text. Any suggestions on how to achieve this? ...

Requiring a form input to be exactly 11 characters long

Currently, I have set it up to tab on Enter key press, but I want it to only move to the next element if there are exactly 11 characters entered. How can I achieve this? function getNextElement(field) { var form = field.form; for (var e = 0; e & ...

Delete the HTML 5 validation for every element in the code

Is there a way to eliminate HTML 5 validation from all input elements using only pure JavaScript? I am considering creating a file that developers can include to add certain functionalities, like removing required attributes, clearing post data, toggling ...

Having issues with loading THREE.js object within a Vue component

I'm baffled by the interaction between vue and THREE.js. I have the same object that works fine in a plain JS environment but not in vue.js. The canvas remains empty in vue.js and the developer console displays multiple warnings. The code I used in J ...

Troubleshooting Bootstrap 5 dropdown display issue triggered by JavaScript

I am attempting to display a dropdown using JavaScript, but it appears there is an issue with Bootstrap 5. When trying to show the dropdown, an exception is thrown: Uncaught TypeError: Cannot read property 'classList' of undefined at _e.show (dro ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

The swiper slider loop malfunctions when the number of slides is less than the double-value

When using **6 slides** with slidesPerView: 3, everything works fine. However, if I use 5 slides and set slidesPerView: 3, the loop stops after the last slide. var swiper = new Swiper('.swiper-container', { direction: 'ver ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

I'm trying to retrieve information from openweathermap in order to show it on my app, but I keep running into an error that says "Uncaught RangeError: Maximum

I recently created a div with the id 'temporary' in order to display data retrieved from the openweathermap.org API. However, I am encountering an error in the console and I'm not sure why. This is my first time working with APIs and I would ...

Set the value of this input element to its current value decreased by

I currently have several tabs with input fields on each tab. I have assigned the same class to each input field so that I can transfer values from one tab to another using the following code: $('.group_input1').change(function(){ $('.g ...

What is the best way to pass value to a URL in a React JS application?

Is there a way to properly use history.push in React to push text to the URL route manually? I am trying to achieve this in my onChange method for an input field: function Header(props) { return ( <div> <input type="radio" onChan ...

Ways to retrieve the React Router match object in mapStateToProps

Is there a way to access the react-router match object for its params from mapStateToProps or any other selector? I'd like to use these params to generate a value that will be passed down as props to a presentational component within the selector. The ...

Can PHP Webpage Make an AJAX POST Request to Express Server on the Same or Different Ports?

Trying to enable a POST request through AJAX from a site to an express server triggered some unexpected challenges. When running the server on the same localhost port as the website (localhost:8080), the webpage fails to render and an error message pops up ...