vue3封裝Notification組件的完整步驟記錄
跳過新手教程的小白,很多東西都不明白,不過是為了滿足一下虛榮心,寫代碼的成就感
彈窗組件的思路基本一致:向body插入一段HTML。我將從創(chuàng)建、插入、移除這三個方面來說我的做法
先來創(chuàng)建文件吧
|-- packages |-- notification |-- index.js # 組件的入口 |-- src |-- Notification.vue # 模板 |-- notification.ts
創(chuàng)建
用到h,render,h是vue3對createVnode()的簡寫。h()把Notification.vue變成虛擬dom,render()把虛擬dom變成節(jié)點。render在渲染時需要一個節(jié)點(第二個參數(shù)),創(chuàng)建一個只用來裝Notification.vue的容器,我要的只是Notification.vue里面的HTML結(jié)構(gòu),所以創(chuàng)建了container先將vm變成節(jié)點,也就是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中能渲染出來,在這里需要先轉(zhuǎn)成虛擬dom再轉(zhuǎn)成節(jié)點
插入
通過document.body.appendChild把這個節(jié)點內(nèi)的第一個子元素插入body中,這樣就能在頁面上顯示出來了。
document.body.appendChild(container.firstElementChild)
移除
vue不能直接操作dom,只能操作虛擬dom了,用null覆蓋掉原來的內(nèi)容即可
render(null, container)
沒懂vue實現(xiàn)原理也只是把效果做出來而已,網(wǎng)上查閱資料也差不多一個月了才做出來,看來我確實不適合編程
完整代碼
// 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) // 手動關(guān)閉 function close() { render(null, container) } } export default notification
在App.vue中使用
// App.vue <script setup lang="ts"> import { BNotification } from "../packages" BNotification() </script>
總結(jié)
到此這篇關(guān)于vue3封裝Notification組件的文章就介紹到這了,更多相關(guān)vue3封裝Notification組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vant使用datetime-picker組件設(shè)置maxDate和minDate的坑及解決
這篇文章主要介紹了vant使用datetime-picker組件設(shè)置maxDate和minDate的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Vue props 單向數(shù)據(jù)流的實現(xiàn)
這篇文章主要介紹了Vue props 單向數(shù)據(jù)流的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11vue?el-switch初始值(默認(rèn)值)不能正確顯示狀態(tài)問題及解決
這篇文章主要介紹了vue?el-switch初始值(默認(rèn)值)不能正確顯示狀態(tài)問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10