Vue 3.0 plugin showToast

858 阅读1分钟
/** index.vue **/<template>
  <div class="ui-toast-mask">
    <div class="ui-toast tc">
      <span class="fs30">{{text}}</span>
    </div>
  </div>
</template>

<script lang="ts" setup>

  interface Props {
    text: string
  }

  withDefaults(defineProps<Props>(), {
    text: '',
    required: true
  })

</script>
/** index.vue **/

/** index.ts **/

import { createVNode, render, App } from "vue"
import Toast from "./index.vue"

export default {
  install (app: App): void {
    let vm = null
    let isClick = true
    const container = document.createElement("div")
    app.config.globalProperties.$showToast = (text: string) => {
      if (!isClick) {
        return
      }

      if (!vm) {
        vm = createVNode(Toast as any, { text })
      }
      isClick = false
      render(vm, container)
      document.body.appendChild(container)
      setTimeout(() => {
        if (vm) {
          container.parentNode.removeChild(container)
          isClick = true
          vm = null
        }
      }, 2000)
    }
  }
}

/** index.ts **/
main.ts 使用
import { createApp, defineComponent, getCurrentInstance } from "vue"

import App from "./App.vue"
import showToast from "./showToast"
const app = createApp(App)
app.use(showToast)

export defualt defineComponent({
  setup () {
    const { proxy: {  $showToast } } = getCurrentInstance()

    const toastText = () => {
      $showToast('hello')
    }
  }
})