作文 api 使用这个

Composition api use this

我正在使用 Vue 3 with Composition API,我想使用第三方包(例如 @meforma/vue-toaster),应该这样使用(在 Options API):

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

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

然后在组件中:

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`);

但是 this 在 Composition API 的 setup() 函数中不起作用。

设置函数在创建组件之前运行一次。它缺少 this 上下文,并且可能不是您想要放置它们的地方。您可以尝试将其放入可以通过按钮调用的方法中。

@meforma/vue-toaster installs $toast on the application context,可从getCurrentInstance().appContext.globalProperties访问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>

我也遇到了同样的问题。 所以我找到了简单的方法: 我正在使用 Vite 顺便说一句。 我的 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')

我的组件:


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

希望对您有所帮助