walemy
walemy

Reputation: 87

Composition api use this

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.

Upvotes: 3

Views: 2929

Answers (3)

tony19
tony19

Reputation: 138206

@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>

UPDATE: getCurrentInstance() is an internal API, so it can be removed at any time. Use it with caution.

Upvotes: 8

user3190147
user3190147

Reputation: 41

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

Upvotes: 1

Daniel
Daniel

Reputation: 35684

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.

Upvotes: 0

Related Questions