Looks like an error has occurred: "Swal has not been defined"

I'm currently working on a small project that involves using CodeIgniter, VueJs, and the Sweet Alert Javascript library. However, I encountered an error in my console stating

ReferenceError: "Swal is not defined"
when I try to call swall.fire({}) within my VueJs methods. Here is a snippet of my code:

deleteCustomers(customer_id){
        Swal.fire({
           title: 'Are you sure?',
           text: "You won't be able to revert this!",
           icon: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#3085d6',
           cancelButtonColor: '#d33',
           confirmButtonText: 'Yes, delete it!'
           }).then((result) => {
              axios.post('/Thirdparty/deleteCustomers', {id : customer_id}).then(function(response){
                 console.log(response.data);
                 //alert(response.data.error);
                 Swal.fire(
                 'Deleted!',
                 'Your file has been deleted.',
                 'success'
                 );
              });
           });
     }

It's worth noting that I have already imported Swall using: import Swal from 'sweetalert2';

NB: swall.fire only seems to fail inside Vuejs methods.

Answer №1

If you're looking to add Sweet Alert to your Vue.js project, here is a simple way to do it:

npm install sweetalert2

In your app.js file, register Sweet Alert so that it can be used in all components:

import swal from 'sweetalert2';
window.Swal = swal;

After this setup, you can easily use Sweet Alert in any component, like in the following Example.vue:

<template>
  ...
</template>
<script>
   export default{
     methods:{
       test(){
         Swal.fire('Test!', 'Hello test message','success');
      } 
    }
   }

For more Sweet Alert methods and details, visit this link.

Answer №2

Swal (with a capital "S") and Swal.fire() were introduced in sweetalert2 version > 7.20.0.

In versions prior to 7.20.0, you should use swal({options}) instead.

Additionally, remember to import it with a capital "S" if you are using npm:

import Swal from 'sweetalert2'

Answer №3

Ensure Sweet Alert is globally accessible in all components by registering it in your main.js file.

import sweetAlert from 'sweetalert2';
window.sweetAlert = sweetAlert;

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

Is it feasible for a form button to perform multiple actions simultaneously?

I am interested in exploring the possibility of having a submit form button perform multiple actions. Currently, I have a custom form that is sent to a Google Spreadsheet using AJAX and I am also utilizing the Blueimp Jquery File Upload plugin. My goal is ...

Every time I try to utilize "useCallback," it results in a TypeError error popping up

I am struggling with an issue related to a const experience that involves creating 6 experiences with their respective popovers. I have been instructed to use useCallback, but every time I attempt to do so, I encounter an error message. This relates to my ...

Passport JS allows you to create a secure login form that redirects users to different URIs based on their role

Currently, I am utilizing Passport JS for authentication management and Express JS to handle routing within my application. At the moment, I have a login route that directs to the /teacher URI upon successful authentication (as depicted below). app.post( ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

Utilizing v-model alongside various JavaScript plugins within a single select element

I've incorporated the jQuery plugins select2 and datepicker into my project, utilizing custom directives for them. Everything was functioning smoothly until I attempted to retrieve the selected value using v-model, which resulted in a failure to bind ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

Learn the process of incorporating hyperlinks into individual table entries with the PrimeVue DataTable component

The default setup of PrimeVue library does not support this feature. Here is how the Table currently appears: example image. Displayed below is an array containing product information: products: [ {brand: "Volkswagen", year: 2012, color: ...

What is the proper way to address the issue of nesting ternary expressions when it comes to conditionally rendering components?

When using the code below, eslint detects errors: {authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />} Error: Avoid nesting ternary expressions. eslint(no-nested-t ...

Issue encountered when trying to attach a hover event to the items in a comb

Currently, I am facing a specific situation. The requirement is to display a custom tooltip when the mouse hovers over the combobox items (specifically the "option" tag). Initially, my solution involved using the title tag. While this method worked effecti ...

Is it possible to change the src attribute after the page has loaded and execute it

A. I'm trying to figure out how to dynamically change the src attribute of an image using JavaScript after the page has loaded. <img src="http://example.com/image.png" /> to <img src="http://domain.com/different.jpg" /> B. Another questi ...

Storing data from an API response into the localStorage using Vue.js upon clicking

My objective is to save specific data in the browser's localStorage upon clicking a link. However, the output I receive is either undefined or completely empty. <li v-for="(category, index) in categories" :key="index"> ...

The Next.js application is functioning smoothly in development, but encounters errors during the building and deployment processes

While my Next.js app compiles and runs smoothly locally during development (using npm run dev), I encounter a failed build when attempting to compile the project (using npm run build). After researching online, it seems that unhandled promises may be the c ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Leveraging the useRoute() function with Vue 3 Composition API and Typescript: [Vue alert]: The injection "Symbol(route location)" was not detected when employing Typescript

Just recently, I upgraded a Vue 2 application that heavily uses Vue Router and TypeScript to Vue 3. During the migration process, I switched a function from reading the route using this.$route in the Options API to using useRoute() in the Composition API. ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Experiencing a lack of content in an Express response

Currently utilizing express to manage a POST request, but encountering an issue when sending the body using node-fetch. After sending the body and logging it in express (server-side code), I am seeing an empty object. The reason behind this behavior remain ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

Retrieve the value of a field from a Formik form integrated with Material UI

I've been working on a way to disable a checkbox group depending on the selected value of a radio group. I took inspiration from the technique outlined in the final section of the Formik tutorial. Using React context has definitely helped clean up the ...