Giter Site home page Giter Site logo

shakee93 / vue-toasted Goto Github PK

View Code? Open in Web Editor NEW
2.2K 24.0 192.0 7.43 MB

๐Ÿ–– Responsive Touch Compatible Toast plugin for VueJS 2+

Home Page: https://shakee93.github.io/vue-toasted/

License: MIT License

JavaScript 84.19% Vue 0.15% SCSS 15.66%
toast vue vue-toasted responsive touch-compatible toast-plugin notification vue-notification toastr

vue-toasted's Introduction

Gitpod Ready-to-Code

Introduction

Vue Toasted is one of the best toast plugins available for VueJS. It's used by VueJS, Laravel, NuxtJS and trusted by many more organizations. It's responsive, touch compatible, easy to use, attractive and feature rich with icons, actions, and more!

Interactive Demo

Checkout the Interactive Demo here.

Menu

Installation

Install using npm

# install it via npm
npm install vue-toasted --save

Install using yarn

# install it via yarn
yarn add vue-toasted

Direct usage with html

<!-- Insert the vue core before vue-toasted -->
<script src="https://unpkg.com/vue-toasted"></script>

<script>
    Vue.use(Toasted)
</script>

Nuxt ๐Ÿ’“ Officially uses vue-toasted for their toast module.

installation guide ๐Ÿ‘‰ @nuxtjs/toast

Usage

It's simple. A couple of lines is all you need.

// register the plugin on vue
import Toasted from 'vue-toasted';

// or you can use it with require
var Toasted = require('vue-toasted').default

Vue.use(Toasted)

// you can also pass options, check options reference below
Vue.use(Toasted, Options)

;
// you can call like this in your component
this.$toasted.show('hello billo')

// and also
Vue.toasted.show('hola billo');

All Good Now you have this cool toast in your project..

Icons ๐Ÿ”ฅ

Material Icons, Fontawesome and Material Design Icons are supported. you will have to import the icon packs into your project. example using icons

{
    // pass the icon name as string
    icon : 'check'

    // or you can pass an object
    icon : {
        name : 'watch',
        after : true // this will append the icon to the end of content
    }
}

Actions ๐Ÿ”ฅ

You can have single or multiple actions in the toast. take a look at the example below

Check below Vue Router section for router integration

Parameter Type Default Description
text* String - name of action
href String null url of action
icon String null name of material for action
target String null target of url
class String/Array null custom css class for the action
push Object null Vue Router push parameters
onClick Function(e,toastObject) null onClick Function of action
Examples
{
    // you can pass a single action as below
    action : {
        text : 'Cancel',
        onClick : (e, toastObject) => {
            toastObject.goAway(0);
        }
    },

    // you can pass a multiple actions as an array of actions
    action : [
        {
            text : 'Cancel',
            onClick : (e, toastObject) => {
                toastObject.goAway(0);
            }
        },
        {
            text : 'Undo',
            // router navigation
            push : {
            	name : 'somewhere',
            	// this will prevent toast from closing
            	dontClose : true
             }
        }
    ]
}

API

Options

below are the options you can pass to create a toast

Option Type Default Description
position String 'top-right' Position of the toast container
['top-right', 'top-center', 'top-left', 'bottom-right', 'bottom-center', 'bottom-left']
duration Number null Display time of the toast in millisecond
keepOnHover Boolean false When mouse is over a toast's element, the corresponding duration timer is paused until the cursor leaves the element
action Object, Array null Add single or multiple actions to toast explained here
fullWidth Boolean false Enable Full Width
fitToScreen Boolean false Fits to Screen on Full Width
className String, Array null Custom css class name of the toast
containerClass String, Array null Custom css classes for toast container
iconPack String 'material' Icon pack type to be used
['material', 'fontawesome', 'mdi', 'custom-class', 'callback']
Icon String, Object null Material icon name as string. explained here
type String 'default' Type of the Toast ['success', 'info', 'error']
theme String 'toasted-primary' Theme of the toast you prefer
['toasted-primary', 'outline', 'bubble']
onComplete Function null Trigger when toast is completed
closeOnSwipe Boolean true Closes the toast when the user swipes it
singleton Boolean false Only allows one toast at a time.

Methods

Methods available on Toasted...

// you can pass string or html to message
Vue.toasted.show( 'my message', { /* some option */ })
Method Parameters Description
show message, options show a toast with default style
success message, options show a toast with success style
info message, options show a toast with info style
error message, options show a toast with error style
register name, message, options register your own toast with options explained here
clear - clear all toasts

Toast Object

Each Toast Returns a Toast Object where you can manipulate the toast.

// html element of the toast
el : HtmlElement

// change text or html of the toast
text : Function(text)

// fadeAway the toast. default delay will be 800ms
goAway : Function(delay = 800)

using the toast object

let myToast = this.$toasted.show("Holla !!");
myToast.text("Changing the text !!!").goAway(1500);

Vue Router

Adding vue-router to vue-toasted where you can use it on toast actions.

// your app router instance
var router = new VueRouter({
	mode: 'history',
	routes: [{
		path: '/foo',
		name : 'foo-name'
	}],
	linkActiveClass: "active"
});

// pass it to vue toasted as below..
Vue.use(Toasted, {
	router
});

Custom Toast Registration

You can register your own toasts like below and it will be available all over the application.

Toasted.register methods api details...

Parameter Type Default Description
name* String - name of your toast
message* String/Function(payload) - Toast Body Content
options String/Object {} Toast Options as Object or either of these strings ['success', 'info', 'error']

Take a look at the below examples

Simple Example
import Toasted from 'vue-toasted';
Vue.use(Toasted);

// Lets Register a Global Error Notification Toast.
Vue.toasted.register('my_app_error', 'Oops.. Something Went Wrong..', {
    type : 'error',
    icon : 'error_outline'
})

After Registering your toast you can easily access it in the vue component like below

// this will show a toast with message 'Oops.. Something Went Wrong..'
// all the custom toasts will be available under `toasted.global`
this.$toasted.global.my_app_error();
Advanced Example

You can also pass message as a function. which will give you more power. Lets think you need to pass a custom message to the error notification we built above.

this.$toasted.global.my_app_error({
    message : 'Not Authorized to Access'
});

you can register a toast with payload like below on the example.

import Toasted from 'vue-toasted';
Vue.use(Toasted);

// options to the toast
let options = {
    type : 'error',
    icon : 'error_outline'
};

// register the toast with the custom message
Vue.toasted.register('my_app_error',
    (payload) => {

        // if there is no message passed show default message
        if(! payload.message) {
    	    return "Oops.. Something Went Wrong.."
        }

        // if there is a message show it with the message
        return "Oops.. " + payload.message;
    },
    options
)

Browsers support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
iOS Safari
iOS Safari
Chrome for Android
Chrome for Android
IE10, IE11, Edge last 7 versions last 7 versions last 7 versions last 7 versions last 3 versions last 3 versions

Please Report If You have Found any Issues.

Mobile Responsiveness

On Mobile Toasts will be on full width. according to the position the toast will either be on top or bottom.

Contribute using the one-click online setup.

Contribute to Vue Toasted using a fully featured online development environment that will automatically: clone the repo, install the dependencies and start the webserver.

Open in Gitpod

Credits

  • Inspired and developed from materialize-css toast.
  • Uses hammerjs for touch events
  • Uses lightweight and fast animejs for animations.
  • Whoever contributes to this project ๐Ÿ˜‰

Enjoy Toasting !!

vue-toasted's People

Contributors

anseljh avatar crustyjew avatar davidsandoz avatar detinho avatar guanzo avatar ivanfretes avatar jezmck avatar kahirokunn avatar kedbers avatar neverbehave avatar newapx avatar nisarhassan12 avatar oller avatar orblazer avatar paulgv avatar qw3ry avatar robinchow avatar robjbrain avatar sceat avatar shakee93 avatar sinchang avatar toilal avatar viktor-ku avatar yckimura avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-toasted's Issues

Request: Typescript types/definition files

This is a great library, that I'd love to use in my project, however, my project is entirely Typescript - and I'm still a bit of a TS noob, so I'm not entirely sure how to create TS definitions that also interact with the Vue plugin system.

I've tried some permutations, but each one falls over at some point - from compilation all the way to runtime.

I think right now, the biggest problem for me is that TS can't seem to pick up the this.$toasted variable, even though I'm following https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins and basically copied what Vue-Router did.

If there are any TS devs with more experience pulling 3rd party plugins in, I'd be happy to get something running and do a PR

Clear toasts when route changes

I don't know if this is already possible or it's a possible future feature but it would be very useful to be able to clear all toasts when the page changes.

Let's say you are showing a success message in a form and you have a call to action to "proceed" ... The message will stay there indefinitely unless you manually trigger something that clears it.

It would be awesome if we could somehow bind it to route changes.

jquery - dependency was not found ???

This dependency was not found:

  • jquery in ./~/velocity-animate/velocity.js

Velocity is an animation engine with the same API as jQuery's $.animate(). It works with and without jQuery.

Download Velocity, include it on your page, and replace all instances of jQuery's $.animate() with $.velocity().

minified/production jQuery undefined error.

Hi,

We are using jQuery 3.1.1 and getting "Uncaught TypeError: Cannot read property 'jQuery311050336921825352572' of undefined" when running gulp mode in production.

Can you kindly look into this.

Thanks

No link to pay shakee93 a coffee

This is unacceptable, how there is no link to pay you a cup of tea, coffee or a bear?

Proposed solution: Please add a BTC address or paypal for donations.

Thank you for this repo!

Featured Request: Block UI

Provide the option to block the rest of the UI when a notification has an action to prevent the user from clicking somewhere else why an action needs to be taken.

Right now this can be accomplished by adding a css class to the toasted container, and then styling that class to block everything else, but a simple boolean in options would be nice.

Mobile toasts not appearing at bottom

I know from reading the issues here and testing the demo site that the toasts are supposed to appear full width at the bottom of the page while on mobile. However on my site the config position is retained regardless of device or screen width.

My site is using Bootstrap 4. How can I get this behavior?

How to use without npm or nodejs.

I have a light web app which contains just one html and few css and js files. I don't want to install npm, because it is not necessary.

So, How could I use this beautiful lib with out npm? I want it to act as Jquery or vue, which just include a few of js and css files, no npm, no nodejs.

Only one toast at a time

Is there a way to globally prevent that no more than a single toast is shown simultaneously? I'm trying to prevent this from happening:

screenshot_1

I know I could just use the recently-added clear method but it seems a bit too overwhelming to have to make that call each time I trigger a toast. I was wondering if I could clear all toasts as soon as a new one is shown.

Show/hide notification

is it possible to create a notification and when we need we can call show it or hide it.

at the moment the only solution I've found is to call this.$toasted.clear() but it will clear all notifications, not the one I am dealing with.

thanks for your time, really nice plugin

mobile position off screen

On the demo site it seems when it comes from the bottom it is not fixed to viewport but the page height, thus appearing beneath the screen area and invisible. at least it did after scrolling around a few times.

can not set global options if I use script tag for vue.

// register plugin if it is used via cdn or directly as a script tag
if (typeof window !== 'undefined' && window.Vue) {
    window.Vue.use(Toasted);
}

Vue.use automatically prevents you from using the same plugin more than once, so calling it multiple times on the same plugin will install the plugin only once.

so I can not set global options by Vue.use(Toasted, options).

Trigger onComplete event when goAway function is called

In order do allow user to close toaster we want to add action for that. If we call goAway function when action is clicked onComplete is never fired, and we relay heavily on onComplete callback.
It would be great if this feature could be added.

Error when using custom toast: Cannot read property 'push' of undefined

First, thanks for an excellent project, this is the best Vue toast library out there.

I seem to be getting the following error when using a custom toast.

This didn't happen in 1.1.15, I just upgraded today to 1.1.18, tested and the error occurs in 1.1.16 as well. I reworked this code from an older style but I still get the error.

TypeError: Cannot read property 'push' of undefined at _show (eval at <anonymous> (http://localhost:8080/app.js:7718:1)

I tried to make a jsfiddle for this, it much easier to reproduce in a brand new vue init webpack

As you can see I have defaults set for normal toasts and I register a global toast. Add this to a boilerplate vue-cli main.js to reproduce along with the App.vue below.

Vue.use(Toasted, {
  position: 'top-right',
  duration: 5000,
  theme: 'primary'
})
Vue.toasted.register('fooNotification',
  (thisVue) => {
   // Normally I use thisVue in here to resolve some routes from thisVue.$router
    var toastContent = '<p>some toast content</p>'
    return toastContent
  },
  {type: 'info',
    position: 'bottom-right',
    duration: null,
    className: 'foo',
    onComplete: function () {
      // foo
    },
    action: {
      text: 'X',
      onClick: (e, toastObject) => {
        // foo
        toastObject.goAway(0)
      }
    }
  }
)

I activate this global toast in App.vue as part of the created hook. The error occurs regardless of where/when I activate the toast.

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

<script>
export default {
  name: 'app',
  methods: {
    fooNotification: function () {
      this.$toasted.global.fooNotification(this)
    }
  },
  created: function () {
    this.fooNotification()
  }
}
</script>

Thanks for taking a look.

position error

When I set the screen to the Iphone 6 ,toast will always be shown at the bottom,set position has no effect.

Showing toastr message after redirect

Hi @shakee93,

Thank you for amazing plugin for vuejs. I have specific need and I am unable to do this using your plugin.
I want to show toastr message once I redirect a route using router-link in VueJs, Let's put this into an example, After user is created I want to redirect user to all users list and show toastr of success message, could you please guide me how can I achieve this.

Thank you.

Singleton Option: There's no delay between toasts.

When I show multiple toasts in quick succession of each other with the singleton option set to true, the toasts quickly flash past leaving only the last one in the sequence. This makes it near impossible to read the messages all the toasts save the very last one.

I suggest that the toasts be displayed one by one. They would use the normal delay, fade away, and then after a configurable delay the next toast would be displayed.

Nuxt.js <3 Toasted

Hi! Just wanted to inform you we have updated @nuxtjs/toast module to 2.0.0 using toasted. This module helps users quickly adding vue-toasted to their Nuxt project. Would be awesome if you can add a link to module in official README.

Thanks.

Don't show toastr when Session expires

Hi @shakee93,

I want to clear all previous toaster messages if session expires, for example, let's say the session expires and if user clicks on any link then User is redirected to Login page with toastr being shown with errors message, but I don't want to show that error toastr instead I am showing some other message, could you help me achieve this?

Thank you,

Mobile toast position

Thanks for this amazing add-on! It would be great to have an option to select the position of toasts on mobile i.e. top or bottom.

Dismiss / Close button

Thank you for releasing this plugin - very nice. I noticed for 'infinite' duration toasts, you can dismiss by clicking and dragging the toast to the side. Is there an option to display a 'close' button?

Babelify vue toasted ?

Hello,
I'm using this component in my vueJs project, but apparently there are Object.assign method which are not polyfilled in your min.js.
Is it possible to babelify it ?

Full width option

Really like this plugin! Great Job!

I would like to have a full width option where the notification is aligned at the top. Is this possible?

License?

Hey, very nice and useful library. However, the license is unclear. Would you consider adding it?

support router-link in toasts

Please add support of router-link in toasts.
For example when creating a user named "Milad", toast text should be "User Milad created successfully" and "Milad" should be linked to "users/10".

The size of min file?

Just noticed the size of min file is 26.6kb from the dist folder? Is it really true or am I interpreting incorrectly?

typeof returns 'object' instead of 'array' in createAction

This action.class option is undocumented as far as I can tell, but it is a valuable feature for adding selectors for test automation.

In the createAction function, there is a switch on typeof action.class that then expects either a string or array, but typeof only returns object for arrays. Using a string as a fallback works, but fixing this would require additional logic to check if the object is an array.

switch (typeof action.class) {

Feature Request: Adjust Offset

Great Work !!!

Hopefully you can add a way to adjust the offset, or at least an option for no offset at all to make it work both as a toast and snackbar.

Font Awesome 5

Any plan to support Font Awesome 5 icon?

I manage to hack up a solution, but it would be great to have official support for it.

Use the following code to load Font Awesome 5 Icon with vue-toasted.

import fontawesome from '@fortawesome/fontawesome'
import faSolid from '@fortawesome/fontawesome-free-solid'

Vue.toasted.show(`${fontawesome.icon(faSolid.faCoffee).html} Hello`, {
  type: 'success',
  duration: 3000
})

For spacing and margin, include the following css.

.toasted-container .toasted > svg {
  margin-right: .5rem;
  margin-left: -.4rem;
}

https://code.luasoftware.com/tutorials/vuejs/vue-toasted-with-font-awesome-icon/

Change word-break to keep-all

I like using this plugin, but i don't think it should break the words with the word-break: break-all,
its not aesthetically pleasing

custom template

Hi, I have 2 questions:

  1. is there a option to setup custom template for toasts? for example when I call success message: this.$toasted.success('Added succesfully') I would like to add some icon from fontawesome...
  2. is there a option to add 'on-click' handler for toast to close it ?

Feature request: global toast handler

Hi,

I really like your project!

At the moment I'm implementing error messages in a web application. The problem is that sometimes the errors have specific properties I want to "toast" and sometimes I just want to print out a generic error message.

I could treat every single error. But this would result in repetitive code. What I really need is something like an function which would be called after invoking a new toast:

function handleError(error) {
  if (error.specificProperty) {
    return error.specificProperty
  }
  return "An error occured."
}

It would be neat If I could pass a function like this to the options object of vue-toasted and every toast (or just errors) could be handled with this function.

Cannot show different messages in global toast

When I register a global toast like this:

Vue.toasted.register('my_app_error', message => {
  return message || 'Oops.. Something Went Wrong..';
}, {
  type: 'error'
});

It works fine if I use this:

this.$toasted.global.my_app_error("Hello");

However if I subsequently call the toast with a different message, the first message is displayed instead:

this.$toasted.global.my_app_error("Bye Bye"); // Toast shows "Hello"

It seems like the message is being cached.

Repro JSFiddle link: https://jsfiddle.net/q7f0Lmf5/1/

No style...

The code below renders the toast without the border. Should I include some css or something?

    this.$toasted.show('Posted!', {
      theme: 'outlined',
      position: 'top-right',
      duration: 2000
    })

Calling goAway() on global toast causes "Cannot read property 'includes' of undefined" and toast does not clear

It looks like the instance.cached_options object is empty on global toasts.

For the moment I just modified the if in _goAway to check if position is defined and avoid the error:
if (instance.cached_options.position && instance.cached_options.position.includes('bottom')) {

This is the definition of the global toast done in main.js right after setting up Toasted.

Vue.use(Toasted, {
  position: 'top-right',
  duration: 5000,
  theme: 'primary'
})
Vue.toasted.register('cookieNotification',
  (thisVue) => {
    // Use thisVue instance to resolve some routes in here
    var toastContent = 'some notification content'
    return toastContent
  },
  {type: 'info',
    position: 'bottom-right',
    duration: null,
    className: 'cookie-alert',
    onComplete: function () {
      var d = new Date()
      d.setTime(d.getTime() + (14 * 24 * 60 * 60 * 1000))
      var expires = 'expires=' + d.toUTCString()
      document.cookie = 'cookieNotice=true;' + expires + ';path=/'
    },
    action: {
      text: 'X',
      onClick: (e, toastObject) => {
        var d = new Date()
        d.setTime(d.getTime() + (14 * 24 * 60 * 60 * 1000))
        var expires = 'expires=' + d.toUTCString()
        document.cookie = 'cookieNotice=true;' + expires + ';path=/'
        toastObject.goAway(0)  //This is where the issue occurs
      }
    }
  }
)

Cannot set custom message for global toasts

If I register a global toast as follows:

Vue.toasted.register('error', 'Error', {
  type: 'error',
  icon: 'exclamation-circle',
  iconPack: 'fontawesome',
  position: 'bottom-right',
  duration: 3000,
});

And then I call the toast with a custom message (from the example in the README):

this.$toasted.global.error({ message: 'My custom error message' });

I get a toast which says Error, instead of My custom error message.

However, if I register the global toast with a function instead of a string, it works.

Is this intentional or a bug?

Compability with vue-fontawesome

I am using the vue-fontawesome components for all the icons in my project, so is there a way to use this with it?

The component looks like this:
<font-awesome-icon :icon="['far', 'trash-alt']"></font-awesome-icon>

vue-fontawesome

How to show two toasts with different layout options at the same time

How to show two(or more) different toats with different UI settings (ex: container position) at the same time. Currently, if you show two toasts with different options both will inherit one set of options,

ex: if you go to the demo page and set the duration to 1min and then click on 'Launch Toast' it will appear at the position you selected, now select different position and also select full width option on. and click on 'Launch Toast' you will see all the toasts (previously shown and the new one) will be full width and will also be moved to the new position. Ideally already shown toasts should keep there settings and positions regardless of the new toast settings.

This is very useful in asynchronous calls to back and show different messages to the UI.
It, however, retain the theme without affecting so I think you can make it work for other options (such as position and full-width) as well.

Use case:
we want to show action based toast at the center of the screen without full-width and other error and notifications at the bottom of the screen with full-width, but in current if a notification comes up while user action toast is visible, both will go to the bottom of the screen and will be full-width which is not user experience as suddenly it changes where user needs to click on.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.