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