Vue js implementation of confirmation using Sweet alert

One of the components I am working on in Vue has a comment delete button.

<button class="button" style="background-color: grey;" @click="destroy">Delete</button>

Clicking the button will trigger the method "destroy".

destroy(){
            swal({
                    title: "Delete this comment?",
                    text: "Are you sure? You won't be able to revert this!",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#3085d6",
                    confirmButtonText: "Yes, Delete it!",
                    closeOnConfirm: true
                },
                function(){
                    axios.delete('/comment/' + this.comment.id + '/delete');

                    $(this.$el).fadeOut(300, () => {
                        return toastr.success('Comment deleted.');
                    });
                });
        },

After displaying the confirmation alert, if users click on the confirm button, the deleting process should proceed. However, it seems that the function is not being executed when the user clicks delete. What could be causing this issue?

Answer №1

The this context within the callback function of SWAL refers to the SWAL instance, not the Vue instance! As a result, references like this.comment.id and this.$el may be undefined, causing the function to not execute properly and potentially resulting in a TypeError.

To address this issue,

  • Utilize Arrow Functions

    swal({
      title: "Delete this comment?",
      text: "Are you sure? You won't be able to revert this!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Yes, Delete it!",
      closeOnConfirm: true
    }, () => {
      axios.delete('/comment/' + this.comment.id + '/delete');
      $(this.$el).fadeOut(300, () => toastr.success('Comment deleted.'));
    })
    
  • Store this into a variable

    let inst = this;
    swal({
      title: "Delete this comment?",
      text: "Are you sure? You won't be able to revert this!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Yes, Delete it!",
      closeOnConfirm: true
    }, function onDelete(){
      axios.delete('/comment/' + inst.comment.id + '/delete');
      $(inst.$el).fadeOut(300, () => toastr.success('Comment deleted.'));
    })
    

Answer №2

This particular issue is not just a simple context error. SweetAlert operates on promises, which means you must make your axios request within a Promise.prototype.then() function.

swal({
  title: "Do you want to remove this comment?",
  text: "Are you absolutely certain? This action can't be undone!",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#3085d6",
  confirmButtonText: "Yes, Delete it!",
  closeOnConfirm: true
})
.then( () => {
  axios.delete('/comment/' + this.comment.id + '/delete');
  $(this.$el).fadeOut(300, () => toastr.success('Comment deleted.'));
})

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

JavaScript / jQuery: Retrieve all class names that begin with a certain prefix

I am looking to retrieve classes that start with a specific prefix such as "category-lifestyle" or "category-magazine". This is how the HTML code appears: <article id="post-361" class="et_pb_post post-361 post type-post status-publish format-standard ...

Vue - Enhanced Image Cropper (Error: Unable to retrieve image result from this.$refs.cropper)

I have a crop function for Vue Advanced Cropper similar to the one below: crop() { const { canvas } = this.$refs.cropper.getResult(); if (canvas) { const form = new FormData(); canvas.toBl ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Monitor a function triggered by a click event

Why is my spy test always returning false? I'm attempting to spy on a function that is called during the click event of an element, but it's not working as expected. spec: describe('button', function() { before(function() { this ...

How to activate the menu in AngularJS

Within my application, I have a header that contains various menu items. These menu items are fetched from a service and displayed in the header. When hovering over the main list, the submenus appear. My goal is to highlight the parent item as active when ...

Retrieve Content from a Different Web Page Using Ajax

I recently received permission from another website to pull their RSS feeds, and now I'm trying to figure out what to write in TAG1 and TAG2. This is the specific issue I'm facing: Here is the HTML code (it's an ajaxed page) <!doctype ht ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

What steps should be taken to safely sanitize untrusted JSON data before parsing it with JSON.parse method

How can we properly sanitize a user-provided JSON string to prevent any vulnerabilities before executing JSON.parse(untrustedString)? My main concern revolves around prototype pollution, but I'm also interested in knowing about any other potential ri ...

Creating a Border Length Animation Effect for Button Hover in Material-UI

I'm currently exploring Material-UI and trying to customize a component. My goal is to add a 'Border Length Animation' effect when hovering over the button. Unfortunately, I have yet to successfully implement this animation as intended. For ...

What is the best way to extract the date and pricing information directly from an interactive graph using Python?

My attempt to gather data from a graph using web scraping with the Selenium library was unsuccessful. The graph can be found at this link. from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.mtgprice.com/sets/Ravnica_All ...

Creating an accordion using an array in JavaScript: A step-by-step guide

I'm experimenting with creating an accordion using HTML, CSS, and JavaScript. I've managed to set it up, however, the array text is only displaying in one accordion item and the buttons are not functioning for each individual accordion. Is there ...

Issues with the styling of HTML code

Our website features a main menu with submenus that are intended to be displayed only when hovering over the main menu. However, upon loading the site, the submenu is already visible causing an issue. We need the submenu to appear only when the main menu i ...

JQuery Confetti System

I'm currently working on a project where I want to scatter 50 randomly colored circles, resembling confetti, within a defined box. However, my current code only displays a single black circle in the top left corner of the box. "use stri ...

What is the method to execute a prototype function within another prototype?

I am facing an issue with my JavaScript class and need some help to resolve it. MyClass.prototype.foo = function() { return 0; } MyClass.prototype.bar = function() { return foo() + 1; } Unfortunately, when I try to run the program, it throws an ...

Error with SwitchMap on ActivatedRoute.paramMap

When I try to run the ngOnInit method of my component, I encountered an error with the following line of code. this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); The error mes ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Leveraging a template featuring underscore techniques

I am attempting to utilize the _.select method in order to retrieve an array of individuals that fall under a certain category. This array will be used later in my script to append them to my span tag. Unfortunately, I am encountering an error while trying ...

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

React Typescript Issue: Antd Checkbox value not updating correctly

Hey there, I'm having trouble filling the Checkbox value with my state data as it's not accepting it. Here is the Checkbox Code: <Form.Item label="Active"> <Checkbox value={this.state.selectedRecord.active} /> </Form ...