欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3封裝Notification組件的完整步驟記錄

 更新時(shí)間:2022年03月31日 12:12:46   作者:不會(huì)編程的xxk  
在我們使用vue的開發(fā)過(guò)程中總會(huì)遇到這樣的場(chǎng)景,封裝自己的業(yè)務(wù)組件,下面這篇文章主要給大家介紹了關(guān)于vue3封裝Notification組件的完整步驟,本文通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下

跳過(guò)新手教程的小白,很多東西都不明白,不過(guò)是為了滿足一下虛榮心,寫代碼的成就感

彈窗組件的思路基本一致:向body插入一段HTML。我將從創(chuàng)建、插入、移除這三個(gè)方面來(lái)說(shuō)我的做法

先來(lái)創(chuàng)建文件吧

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

創(chuàng)建

用到h,render,h是vue3對(duì)createVnode()的簡(jiǎn)寫。h()把Notification.vue變成虛擬dom,render()把虛擬dom變成節(jié)點(diǎn)。render在渲染時(shí)需要一個(gè)節(jié)點(diǎn)(第二個(gè)參數(shù)),創(chuàng)建一個(gè)只用來(lái)裝Notification.vue的容器,我要的只是Notification.vue里面的HTML結(jié)構(gòu),所以創(chuàng)建了container先將vm變成節(jié)點(diǎn),也就是HTML,這樣才能插到body中

import { h, render } from "vue"
import NotificationVue from "./Notification.vue"

let container = document.createElement('div')
let vm = h(NotificationVue)
render(vm, container)

懵逼點(diǎn):為什么.vue文件在App.vue中能渲染出來(lái),在這里需要先轉(zhuǎn)成虛擬dom再轉(zhuǎn)成節(jié)點(diǎn)

插入

通過(guò)document.body.appendChild把這個(gè)節(jié)點(diǎn)內(nèi)的第一個(gè)子元素插入body中,這樣就能在頁(yè)面上顯示出來(lái)了。

document.body.appendChild(container.firstElementChild)

移除

vue不能直接操作dom,只能操作虛擬dom了,用null覆蓋掉原來(lái)的內(nèi)容即可

render(null, container)

沒懂vue實(shí)現(xiàn)原理也只是把效果做出來(lái)而已,網(wǎng)上查閱資料也差不多一個(gè)月了才做出來(lái),看來(lái)我確實(shí)不適合編程

完整代碼

// 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>

有個(gè)疑問(wèn)為什么.vue文件在app中又能直接被渲染出來(lái)

// 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)

  // 手動(dòng)關(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論