信息发布→ 登录 注册 退出

vue3封装Notification组件的完整步骤记录

发布时间:2026-01-11

点击量:
目录
  • 创建
  • 插入
  • 移除
    • 在App.vue中使用
  • 总结

    跳过新手教程的小白,很多东西都不明白,不过是为了满足一下虚荣心,写代码的成就感

    弹窗组件的思路基本一致:向body插入一段HTML。我将从创建、插入、移除这三个方面来说我的做法

    先来创建文件吧

    |-- packages
        |-- notification
            |-- index.js # 组件的入口
            |-- src
                |-- Notification.vue # 模板
                |-- notification.ts

    创建

    用到h,render,h是vue3对createVnode()的简写。h()把Notification.vue变成虚拟dom,render()把虚拟dom变成节点。render在渲染时需要一个节点(第二个参数),创建一个只用来装Notification.vue的容器,我要的只是Notification.vue里面的HTML结构,所以创建了container先将vm变成节点,也就是HTML,这样才能插到body中

    import { h, render } from "vue"
    import NotificationVue from "./Notification.vue"
    
    let container = document.createElement('div')
    let vm = h(NotificationVue)
    render(vm, container)

    懵逼点:为什么.vue文件在App.vue中能渲染出来,在这里需要先转成虚拟dom再转成节点

    插入

    通过document.body.appendChild把这个节点内的第一个子元素插入body中,这样就能在页面上显示出来了。

    document.body.appendChild(container.firstElementChild)

    移除

    vue不能直接操作dom,只能操作虚拟dom了,用null覆盖掉原来的内容即可

    render(null, container)

    没懂vue实现原理也只是把效果做出来而已,网上查阅资料也差不多一个月了才做出来,看来我确实不适合编程

    完整代码

    // Notification.vue
    <template>
      <div class="notification">
        Notification
        <button @click="onClose">x</button>
      </div>
    </template>
    
    <script setup lang="ts">
    interface Props {
      onClose?: () => void
    }
    
    defineProps<Props>()
    </script>

    有个疑问为什么.vue文件在app中又能直接被渲染出来

    // notification.ts
    import { h, render } from "vue"
    import NotificationVue from "./Notification.vue"
    const notification = () => {
      let container = document.createElement('div')
      let vm = h(NotificationVue, {onClose: close})
      render(vm, container)
      document.body.appendChild(container.firstElementChild)
    
      // 手动关闭
      function close() {
        render(null, container)
      }
    }
    export default notification

    在App.vue中使用

    // App.vue
    <script setup lang="ts">
    import {
      BNotification
    } from "../packages"
    
    BNotification()
    </script>

    总结

    在线客服
    服务热线

    服务热线

    4008888355

    微信咨询
    二维码
    返回顶部
    ×二维码

    截屏,微信识别二维码

    打开微信

    微信号已复制,请打开微信添加咨询详情!