Categories
JavaScript Vue

Display a Toast in a Vue App with vue-toastr

Spread the love

A toast is a popup notification that has a black background color and disappears after a set time.

To add them easily to our Vue app, we can use the vue-toastr package.

To install it, we run:

npm install vue-toastr

Then we can register the plugin by writing:

import Vue from "vue";
import App from "./App.vue";
import VueToastr from "vue-toastr";
Vue.use(VueToastr);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

Then in our component, we can display a toast by writing:

<template>
  <div id="app"></div>
</template>

<script>
export default {
  mounted() {
    this.$toastr.s("Success", "Success Toast Title");
  }
};
</script>

Display Toast

We display the toast after it’s loaded.

s is for success.

The first argument is the message and the 2nd is the title.

There are also other methods we can display toasts with:

this.$toastr.e("error");
this.$toastr.w("warning");
this.$toastr.i("information");

e is for error, w is for wanting, and i is for information.

Remove Toast

We can remove a toast with the removeByName, Close, or removeByTypeMethods.

For instance, we can create a toast by writing:

const toast = this.$toastr.Add({
  name: "name", 
  msg: "Hi", 
  type: "error"
});

And then write:

this.$toastr.Close(toast);

to close it.

We can also remove it by the name:

this.$toastr.removeByName("name");

The name is the value of the name property we have in the object we passed into Add.

Also, we can remove by type:

this.$toastr.removeByType("error");

We remove all toast with type error.

Options

In addition to name, type and msg, we can also pass in title to set the title.

classNames set the class names for the toast so we can style it.

timeout sets the amount of time before it’s closed.

closeOnHover makes the toast close on hover.

clickClose makes the toast close on click.

It also takes a few event handlers, including onCreated, onClosed, and onClicked, onMouseOver, and onMouseOut.

progressbar lets us enable or disable the progress bar.

And progressBarValue lets us change the initial value of the progress bar.

Conclusion

We can use vue-toastr to create very customizable toasts in our Vue.js apps.

We can change styles, timeouts, open and close toasts in various ways, and much more.

Leave a Reply

Your email address will not be published. Required fields are marked *