Sweet Alert is a beautiful replacement for the default browser alert and confirm boxes and something that I pull into all of my projects. While it provides great functionality, it’s quite verbose and can get quite repetitive. There’s also a maintainability issue because you can pass in properties to style the alert box, so if we decide to change this style later we would have to do it across all of our alert boxes individually – which would be a nightmare in a large app – so we really want to encapsulate much of the repetitive code, while keeping the alert as flexible as possible; and we can do that in Vue using a mixin, which simply allows us to reuse code in our vue components.

The first part of our mixin will be a simple alert method, which will just be a swal (sweet alert) function that we can pass an object to, this allows us to use this.alert() and if in future we want to provide some default options, we can do it here:

var SweetAlert = {
  methods: {
    alert(options){
        swal(options)
    }
  }
}

Now we want a “success” alert, we could do something like this:

successAlert(title, text, showConfirmButton, timer){
  this.alert({
    title: title,
    text: text,
    timer: timer,
    showConfirmButton: showConfirmationButton,
    type: success
  })
}

However, often the parameters we are passing in will be the same. We could set some defaults if the parameter is not passed, but if we wanted to update timer we would still need to pass the preceding parameters, so rather than being forced to do that, let’s allow the method to accept an object and use ES2015's destructuring assignment so we can update only the properties we want:

      alertSuccess({title = "Success!", text = "That's all done!", timer = 1000, showConfirmationButton = false} = {}) {
        this.alert({
          title: title,
          text: text,
          timer: timer,
          showConfirmButton: showConfirmationButton,
          type: 'success'
        });
      }

Now we can pass in any of those properties to only update the ones we want:

this.alertSuccess({text: "Record Updated Successfully!"}) // Update text, keep everything else as the default values

And we can do the same for error:

    alertError({title = "Success!", text = "Update Successul"} = {}){
       this.alert({
         title: title,
         text: text,
         type: 'error'
       });
    }

Finally, let’s set up our confirm alert box. This is a bit different because we will need a callback and and it will be necassary to allow different options to be passed, so rather than using destructuring, which forces us to declare all our object properties upfront, let’s use Object.assign to override any default properties:

confirm(callback, options) {
  options = Object.assign({
    title: "Are you sure?",
    text: "Are you sure you want to do that?",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes",
    closeOnConfirm: false
  }, options); // Override the default with the passed in options using Object.assign.

  swal(options, callback);
}

So we end up with a final mixin looking like this:

var SweetAlert = {
  methods: {
    alert(options) {
        swal(options);
    },
    alertSuccess({title = "Success!", text = "That's all done!", timer = 1000, showConfirmationButton = false} = {}) {
      this.alert({
        title: title,
        text: text,
        timer: timer,
        showConfirmButton: showConfirmationButton,
        type: 'success'
      });
    },
    alertError({title = "Error!", text = "Oops...Something went wrong"} = {}) {  
      this.alert({
        title: title,
        text: text,
        type: 'error'
      });
    },
    confirm(callback, options) {
      options = Object.assign({
        title: "Are you sure?",
        text: "Are you sure you want to do that?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes",
        closeOnConfirm: false
      }, options);

      swal(options, callback);
    }
  }
}

Using The Mixin

Mixins are straight forward to use, you simply supply the mixins you want to use to the mixins property:

new Vue({
  el: "#app",
  mixins: [SweetAlert]
});

Now all methods in the mixin are available, so we can use our alerts using this as our context:

this.alert({title: "Hello World!"});
this.alertSuccess({timer: 2000});
this.alertError();
this.confirm(() => {console.log('OK')});

And here’s the JSFiddle for our complete SweetAlert mixin: https://jsfiddle.net/vuetiful/y1qyjb1d/

Advertisements