2
votes

I am using Vue 3 with Composition API, and I want to use a third-party package (for example @meforma/vue-toaster), and it should be used like this (in Options API):

import Toaster from '@meforma/vue-toaster';

createApp(App).use(Toaster).mount('#app')

and then in the component:

this.$toast.show(`Hey! I'm here`);
this.$toast.success(`Hey! I'm here`);
this.$toast.error(`Hey! I'm here`);
this.$toast.warning(`Hey! I'm here`);
this.$toast.info(`Hey! I'm here`);

But this is not working inside the Composition API's setup() function.

2

2 Answers

3
votes

@meforma/vue-toaster installs $toast on the application context, which can be accessed from getCurrentInstance().ctx in setup():

<template>
  <button @click="showToast">Show toast</button>
</template>

<script>
import { getCurrentInstance } from 'vue'

export default {
  setup() {
    const $toast = getCurrentInstance().ctx.$toast
    return {
      showToast() {
        $toast.show(`Hey! I'm here`)
        $toast.success(`Hey! I'm here`)
        $toast.error(`Hey! I'm here`)
        $toast.warning(`Hey! I'm here`)
        $toast.info(`Hey! I'm here`)
        setTimeout($toast.clear, 3000)
      }
    }
  }
}
</script>
0
votes

The setup function runs one-time before the component is created. It lacks the this context and may not be where you would want to place these anyway. You could try putting it into a method that you can call via a button.