组合 api 使用这个

wal*_*emy 2 vue.js vuejs3 vue-composition-api

我正在使用 Vue 3 和 Composition API,并且我想使用第三方包(例如@meforma/vue-toaster),并且应该像这样使用(在选项 API 中):

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

createApp(App).use(Toaster).mount('#app')
Run Code Online (Sandbox Code Playgroud)

然后在组件中:

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`);
Run Code Online (Sandbox Code Playgroud)

this在 Composition API 的函数内部不起作用setup()

ton*_*y19 7

@meforma/vue-toaster安装$toast在应用程序上下文中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>
Run Code Online (Sandbox Code Playgroud)

UPDATE: getCurrentInstance()一个内部API,因此可以随时删除。请谨慎使用。