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

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

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

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

彈窗組件的思路基本一致:向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é)點(diǎn)。render在渲染時需要一個節(jié)點(diǎn)(第二個參數(shù)),創(chuàng)建一個只用來裝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中能渲染出來,在這里需要先轉(zhuǎn)成虛擬dom再轉(zhuǎn)成節(jié)點(diǎn)

插入

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

document.body.appendChild(container.firstElementChild)

移除

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

render(null, container)

沒懂vue實(shí)現(xiàn)原理也只是把效果做出來而已,網(wǎng)上查閱資料也差不多一個月了才做出來,看來我確實(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>

有個疑問為什么.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)文章

最新評論