Composition api use this

Viewed 1287

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.

3 Answers

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

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

<script>
import { getCurrentInstance } from 'vue'

export default {
  setup() {
    const $toast = getCurrentInstance().appContext.globalProperties.$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>

i've the same issue. So i've found and easy way to do: I'm using Vite BTW. my main.js

import { createApp } from 'vue'
import App from './App.vue'
import Toaster from '@meforma/vue-toaster';

let app = createApp(App)

app.use(Toaster, {
    position: 'top-right'
}).provide('toast', app.config.globalProperties.$toast)
app.mount('#app')

my component:


import { inject } from 'vue'
export default {
    name: 'table-line',
    
    setup(props) {
        const toast = inject('toast');
        toast.success(`it works !`)
        return {toast}
    }
}

Hope it could be helpful

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.

Related