11

I'm working on small project using codeigniter and VueJs and sweet alert javascript library. but i get an error in my console ReferenceError: "Swal is not defined" once i call swall.fire({}) inside my VueJs methods. This is 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'
                 );
              });
           });
     }

and of course i have already imported swall using : import Swal from 'sweetalert2';

NB : swall.fire doesn't work only inside Vuejs methods

Amine Bouhaddi
  • 554
  • 1
  • 7
  • 24
  • it is preferable that you use your own vue components, or maybe you can consider to use this one https://github.com/avil13/vue-sweetalert2 which has always worked well for me – porloscerros Ψ Nov 16 '19 at 16:16
  • 1
    i fixed the bug thank you, solution is i had to do, window.Swol = import ''; – Amine Bouhaddi Nov 16 '19 at 16:25

3 Answers3

17

Here is a quick way to implement Sweet Alert on vue js

npm install sweetalert2

on your app.js register sweet alert to make it accessible in all your components

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

Then in any of the components of example ( Example.vue)

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

More Sweet alert methods can be found here

Felix Runye
  • 2,135
  • 1
  • 20
  • 20
5

Swal (with Capital S) and Swal.fire() is introduced in sweetalert2 version > 7.20.0.

In older versions (< 7.20.0), you should use swal({options}) instead.

Also make sure to import it with capital S, if you're using npm :

import Swal from 'sweetalert2'
yaya
  • 7,675
  • 1
  • 39
  • 38
4

on your main.js register sweet alert to make it accessible in all your components

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