Skip to content

useToasts

A set of methods to manipulate an array of dismissible toasts.

Import

ts
import useToasts from '@leaflink/stash/useToasts';

Usage

Call the composable in your component and push a toast to the toasts array.

vue
<script setup>
  import useToasts from '@leaflink/stash/useToasts';

  const toasts = useToasts({ timeout: 3000 });

  // displays an "info" toast
  const toastId = toasts.info("I am a toast!");

  // logs the currently active/visible toasts
  console.log(toasts.active);

  // removes an active/visible toast
  toasts.remove(toastId);

  // removes all toasts
  toasts.removeAll();
</script>

Variants

The toasts object returned by useToasts() contains methods to display specific variants of the Toast component:

template
<Button @click="toasts.success('Success toast')">Success</Button>
<Button @click="toasts.info('Info toast')">Info</Button>
<Button @click="toasts.error('Error toast')">Error</Button>
<Button @click="toasts.warning('Warning toast')">Warning</Button>

HTML Content

Toasts can also receive a render function instead of a string.

vue
<Button @click="toasts.info(() => h('strong', 'New notification'))">
  Show toast
</Button>

You can also render a Vue component by passing it to the render function.

vue
<template>
  <strong>New Notification</strong><br />
  <strong>[Seller]</strong> has <strong>accepted</strong> the <a>order 1234</a>
</template>
vue
<Button @click="toasts.success(() => h(MyToastContent))">
  Show toast
</Button>

If you need to pass down a template string, the component can safely parse it and inject it to the dom.

vue
  <Button @click="toasts.success('<strong>New Notification</strong><br /><strong>[Seller]</strong> has <strong>accepted</strong> the <a>order 1234</a>')">
    Show toast
  </Button>

INFO

The toast component uses a v-html directive to render the string passed as content. Before rendering it, the component sanitizes the string to avoid a potential XSS attacks.

Duration

By default, a toast will be displayed for 5000 milliseconds before being dismissed. To specify another duration, you can pass the timeout option:

Globally

vue
<script setup>
  const toasts = useToasts({ timeout: 3000 });
</script>

<template>
  <Button @click="toasts.info('I will dismiss in 3 seconds')">
    Show toast
  </Button>
</template>

Locally

vue
<script setup>
  const toasts = useToasts();
</script>

<template>
  <Button @click="toasts.info('I will dismiss in 3 seconds', { timeout: 3000 })">
    Show toast
  </Button>
</template>

INFO

Options informed locally will take precedence over global options.

Permanent

Toasts can also be displayed indefinitely by setting the timeout property to false:

template
<Button @click="toasts.success('Click me to dismiss', { timeout: false })">
  Show toast
</Button>

Config

ts
type ToastOptions = {
  timeout?: number | boolean;
};