• Stars
    star
    763
  • Rank 59,519 (Top 2 %)
  • Language Vue
  • License
    MIT License
  • Created over 1 year ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🔔 An opinionated toast component for Vue.

Sonner for Vue

vue-sonner minzip package size vue-sonner package version

An opinionated toast component for Vue. It's a Vue port of Sonner

Preview

vue-sonner.mp4

Introduction

Vue Sonner is an opinionated toast component for Vue. It's customizable, but styled by default. Comes with a swipe to dismiss animation.

Installation

To start using the library, install it in your project:

pnpm install vue-sonner
or
yarn add vue-sonner

Usage

For Vue 3

<!-- App.vue -->
<template>
  <Toaster />
  <button @click="() => toast('My first toast')">Render a toast</button>
</template>

<script lang="ts" setup>
  import { Toaster, toast } from 'vue-sonner'
</script>

For Nuxt 3

Define a nuxt plugin

// plugins/sonner.client.ts
import { Toaster, toast } from 'vue-sonner'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.component('Toaster', Toaster)

  return {
    provide: {
      toast
    }
  }
})

Use Toaster component and $toast function anywhere in the Vue SFC

<!-- app.vue -->
<template>
  <div>
    <NuxtPage />
    <Toaster position="top-right" />
    <button @click="() => $toast('My first toast')">Render a toast</button>
  </div>
</template>

<script setup lang="ts">
  // alternatively, you can also use it here
  const { $toast } = useNuxtApp()
</script>

Add the build transpile for vue-sonner

// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  ...
  build: {
    transpile: ['vue-sonner']
  }
})

CDN Link

EMS version

https://cdn.jsdelivr.net/npm/vue-sonner/+esm

UMD version

https://www.unpkg.com/[email protected]/lib/vue-sonner.umd.cjs

Types

Default

Most basic toast. You can customize it (and any other type) by passing an options object as the second argument.

toast('Event has been created')

With custom description:

toast('Event has been created', {
  description: 'Monday, January 3rd at 6:00pm'
})

Success

Renders a checkmark icon in front of the message.

toast.success('Event has been created')

Error

Renders an error icon in front of the message.

toast.error('Event has not been created')

Action

Renders a button.

toast('Event has been created', {
  action: {
    label: 'Undo',
    onClick: () => console.log('Undo')
  }
})

Promise

Starts in a loading state and will update automatically after the promise resolves or fails.

You can pass a function to the success/error messages to incorporate the result/error of the promise.

toast.promise(() => new Promise((resolve) => setTimeout(resolve, 2000)), {
  loading: 'Loading',
  success: (data: any) => 'Success',
  error: (data: any) => 'Error'
})

Custom Component

You can pass a Vue Component as the first argument instead of a string to render custom Component while maintaining default styling. You can use the headless version below for a custom, unstyled toast.

<script lang="ts" setup>
  import { defineComponent, h, makeRaw } from 'vue'

  const CustomDiv = defineComponent({
    setup() {
      return () =>
        h('div', {
          innerHTML: 'A custom toast with unstyling'
        })
    }
  })

  toast(makeRaw(CustomDiv))
</script>

Customization

Headless

You can use toast.custom to render an unstyled toast with custom jsx while maintaining the functionality.

<script lang="ts" setup>
import { markRaw } from 'vue'

import HeadlessToast from './HeadlessToast.vue'

toast.custom(markRaw(HeadlessToast), { duration: 999999 })
</script>

Theme

You can change the theme using the theme prop. Default theme is light.

<Toaster theme="dark" />

Position

You can change the position through the position prop on the <Toaster /> component. Default is top-right.

<!-- Available positions -->
<!-- top-left, top-center, top-right, bottom-left, bottom-center, bottom-right -->

<Toaster position="top-center" />

Expanded

Toasts can also be expanded by default through the expand prop. You can also change the amount of visible toasts which is 3 by default.

<Toaster expand :visibleToasts="9" />

Styling for all toasts

You can style your toasts globally with the toastOptions prop in the Toaster component.

<Toaster
  :toastOptions="{
    style: { background: 'red' },
    className: 'my-toast',
    descriptionClassName: 'my-toast-description'
  }"
/>

Styling for individual toast

toast('Event has been created', {
  style: {
    background: 'red'
  },
  className: 'my-toast',
  descriptionClassName: 'my-toast-description'
})

Close button

Add a close button to all toasts that shows on hover by adding the closeButton prop.

<Toaster closeButton />

Rich colors

You can make error and success state more colorful by adding the richColors prop.

<Toaster richColors />

Custom offset

Offset from the edges of the screen.

<Toaster offset="80px" />

Programmatically remove toast

To remove a toast programmatically use toast.dismiss(id).

const toastId = toast('Event has been created')

toast.dismiss(toastId)

You can also use the dismiss method without the id to dismiss all toasts.

toast.dismiss()

Programmatically remove toast

You can change the duration of each toast by using the duration property, or change the duration of all toasts like this:

<Toaster :duration="10000" />
toast('Event has been created', {
  duration: 10000
})

// Persisent toast
toast('Event has been created', {
  duration: Infinity
})

On Close Callback

You can pass onDismiss and onAutoClose callbacks. onDismiss gets fired when either the close button gets clicked or the toast is swiped. onAutoClose fires when the toast disappears automatically after it's timeout (duration prop).

toast('Event has been created', {
  onDismiss: (t) => console.log(`Toast with id ${t.id} has been dismissed`),
  onAutoClose: (t) =>
    console.log(`Toast with id ${t.id} has been closed automatically`)
})

Keyboard focus

You can focus on the toast area by pressing ⌥/alt + T. You can override it by providing an array of event.code values for each key.

<Toaster hotkey="['KeyC']" />

Inspiration

  • sonner - An opinionated toast component for React.

License

MIT @xiaoluoboding

More Repositories

1

vue-command-palette

⌨️ A fast, composable, unstyled command palette interface for Vue.
Vue
519
star
2

bookmark.style

🪄 Turn any link into a stylish visual web bookmark, one-click to copy the beautiful web bookmark image.
Vue
310
star
3

ghost-theme-kaldorei

🎨 A Simple And Elegant Ghost Theme Derive From Default Theme Casper
CSS
291
star
4

vue-demo-collection

A collection of Vue.js demos
Vue
268
star
5

vue-smart-widget

🗃️Smart widget is a flexible and extensible content container component for Vue2.x / Vue3.x in Next branch.
JavaScript
186
star
6

vue-stroll

📜 Vue.js + Stroll.js. Awesome CSS list scroll effects for Vue2.x.
Vue
157
star
7

chrome-ext-starter

⚡️ Modernized Chrome Extension Manifest V3 Vite Starter Template
TypeScript
140
star
8

xiaoluoboding

My GitHub Profile. Before Fork it, Star it, Please. 😂
131
star
9

nuxt3-starter

💚 A Better Nuxt 3 Starter Template,generate by nuxi.
Vue
125
star
10

monthly

📖 聚焦前端,记录过去一个月看到的优秀的文章、工具,丰富前端技术栈。每月28日更新。你可以 Watch 它,相当于订阅。
Shell
105
star
11

repository-tree

🌲Pretty display directory tree view of a GitHub repository.
Vue
71
star
12

self-hosted-app-starter

🪄 A starter for the self-hosted app, help you to build your next full-stack project. https://sha-starter.onrender.com
Go
70
star
13

svg-animation-booklet

《SVG 动画开发实战》小册
Shell
60
star
14

vue-color-wheel

🎨 A color wheel picker for Vue
Vue
49
star
15

awesome-starless

A curated list of awesome repositories with few stargazers but has a huge users.
JavaScript
45
star
16

vercel-metafy

Easily scrape metadata from websites as a service using Vercel.
TypeScript
44
star
17

vue-sfc-sandbox

Vue SFC Sandbox, Sandbox as a Vue 3 component.
Vue
42
star
18

chrome-web-bookmark

One-click turn any link into a visual web bookmark, and it looks Like Twitter cards or Notion web bookmark.
Vue
42
star
19

tech-stack.tools

🗡️ Discover our curated list of creative tools to supercharge your next project.
CSS
39
star
20

skylines

My GitHub story in 3D. View a 3D model of your GitHub contribution graph.
Vue
34
star
21

vue-sfc2esm

Transpiled Vue SFC File to ES modules.
TypeScript
28
star
22

coolshapes-vue

100+ abstract shapes with gradient for design & dev project for Vue
Vue
20
star
23

vue3-starter

🖖 A Better Vue 3 Starter Template,generate by create-vue.
Vue
16
star
24

vuepress-tailwind-theme-starter

A starter of build VuePress Theme with TailwindCss.
Stylus
15
star
25

sql-repl

🔍 Just a SQL REPL for web.
Vue
14
star
26

vuex-stateshot

💾 A State Snapshot plugin on Actions/Mutations for Vuex3.1+.
JavaScript
13
star
27

metafy-svg

Easily crawl a website's metadata and generate SVG as a service.
TypeScript
13
star
28

tailwind-pre-processor

An implementation of tailwindcss using less / stylus / Sass/SCSS.
CSS
11
star
29

vscode-folder-size

📁 Shows the current file | folder size in the status bar for Visual Studio Code
TypeScript
8
star
30

element-demi

An adapter for using Element UI with Vue 2 / 3.
JavaScript
7
star
31

vue-library-starter

My minimal Vue library starter, built on top of Vite & Vue 3
Vue
7
star
32

yii2-guide-cn

Yii2.0 中文指南,Yii2.0 权威指南,Yii2.0 开发教程。
PHP
5
star
33

vue-digit-animation

A digit animation component with wheel/slide effect for Vue 3.
Vue
5
star
34

vue-dashboard

Build A Vue Dashboard Using Cube.js.
Vue
4
star
35

bugshot

团队内部使用,一款可以提交Bug附带截图功能到Redmine的Chrome插件。
JavaScript
4
star
36

algo-data-structures-patterns

📖 Learn data structures、algorithms、patterns using JavaScript.
JavaScript
3
star
37

vue-number-spinner

Number spinner component for Vue.js.
JavaScript
3
star
38

my-first-web3-demo

[WIP] Just for learning Web 3 Tech Stack.
Vue
2
star
39

netlify-metafy

Easily scrape metadata from websites as a service using Netlify.
JavaScript
2
star
40

vuepress-plugin-svg-sprite

🔌SVG Sprite plugin for Vuepress generate with svg-sprite-loader and optimised with svgo-loader
JavaScript
2
star
41

transpile-vue-sfc-to-es-modules

Transpile Vue SFC To ES Modules Slides, Built On Top Of Slidev.
CSS
2
star
42

t-to-g

1
star
43

marketing-website-demo

TypeScript
1
star
44

vue-i18n-practice

A Vue 3 demo for taking some practice use vue-i18n.
Vue
1
star
45

vite-vue2-template

⚡️ Starter template with Vite + Vue2, also support `<script setup>` style.
Vue
1
star
46

taro-echarts-sample

基于Taro使用ECharts示例
JavaScript
1
star
47

wepy-douban-demo

Just another douban weapp demo.
Vue
1
star
48

effective-javascript

68 Specific ways to harness the power of javascript.
1
star
49

image-hub-2021

My personal image hub for 2021.
1
star
50

vuepress-plugin-hero-pattern

🌠A Hero Patterns achievement for VuePress
Vue
1
star
51

astrolabe

Manage your GitHub Stars with One App
Vue
1
star
52

csspen

An interactive CSS demo with live editor and preview. build with Vue.js.
1
star