温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue3如何封装Notification组件

发布时间:2022-03-31 14:44:13 来源:亿速云 阅读:293 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关vue3如何封装Notification组件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

    vue3如何封装Notification组件

    弹窗组件的思路基本一致:向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>

    感谢各位的阅读!关于“vue3如何封装Notification组件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI