第一个封装的toast插件

367 阅读1分钟
//index.ts
import { createVNode, render } from 'vue';
import type { App } from 'vue';
import Toast from './toast.vue';

const myToast = (options: any) => {
  //DOM
  const container = document.createElement('div');
  //虚拟dom
  const vm = createVNode(Toast, options);
  //渲染虚拟dom
  render(vm, container);
  //挂在DOM
  document.body.appendChild(container);
};
export default {
  //类似一个钩子函数
  install: (app: App) => {
    app.config.globalProperties.$myToast = myToast;
  },
};

<template>
  <div class="my_toast">{{ text }}</div>
</template>

<script>
  import { string } from 'vue-types';
  export default {
    props: {
      text: {
        type: string,
        default: '',
      },
    },
    created() {
      console.log('我是封装的组件');
    },
  };
</script>

<style scoped>
  .my_toast {
    position: fixed;
    top: 0;
    left: 0;
    width: 300px;
    height: 150px;
  }
</style>

使用

 const { proxy }: any = getCurrentInstance();
 proxy.$myToast({ text: '我是toast' });