vue3.0實(shí)現(xiàn)插件封裝
最近公司有一個(gè)新的項(xiàng)目,項(xiàng)目框架是我來(lái)負(fù)責(zé)搭建的,所以果斷選擇了Vue3.x+ts。vue3.x不同于vue2.x,他們兩的插件封裝方式完全不一樣。由于項(xiàng)目中需要用到自定義提示框,所以想著自己封裝一個(gè)。vue2.x提供了一個(gè)vue.extend的全局方法。那么vue3.x是不是也會(huì)提供什么方法呢?果然從vue3.x源碼中還是找到了。插件封裝的方法,還是分為兩步。
1、組件準(zhǔn)備按照vue3.x的組件風(fēng)格封裝一個(gè)自定義提示框組件。在props屬性中定義好。需要傳入的數(shù)據(jù)流。
<template> <div v-show='visible' class='model-container'> <div class='custom-confirm'> <div class='custom-confirm-header'>{{ title }}</div> <div v-html='content'></div> <div class='custom-confirm-footer'> <Button @click='handleOk'>{{ okText }}</Button> <Button @click='handleCancel'>{{ cancelText }}</Button> </div> </div> </div></template>
<script lang='ts'>import { defineComponent, watch, reactive, onMounted, onUnmounted, toRefs } from 'vue';export default defineComponent({ name: 'ElMessage', props: { title: { type: String, default: '', }, content: { type: String, default: '', }, okText: { type: String, default: '確定', }, cancelText: { type: String, default: '取消', }, ok: { type: Function, }, cancel: { type: Function, }, }, setup(props, context) { const state = reactive({ visible: false, }); function handleCancel() { state.visible = false; props.cancel && props.cancel(); } function handleOk() { state.visible = false; props.ok && props.ok(); } return { ...toRefs(state), handleOk, handleCancel, }; },});</script>2、插件注冊(cè)
這個(gè)才是插件封裝的重點(diǎn)。不過(guò)代碼量非常少,只有那么核心的幾行。主要是調(diào)用了vue3.x中的createVNode創(chuàng)建虛擬節(jié)點(diǎn),然后調(diào)用render方法將虛擬節(jié)點(diǎn)渲染成真實(shí)節(jié)點(diǎn)。并掛在到真實(shí)節(jié)點(diǎn)上。本質(zhì)上就是vue3.x源碼中的mount操作。
import { createVNode, render } from ’vue’;import type {App} from 'vue';import MessageConstructor from ’./index.vue’const body=document.body;const Message: any= function(options:any){ const modelDom=body.querySelector(`.container_message`) if(modelDom){ body.removeChild(modelDom) } options.visible=true; const container = document.createElement(’div’) container.className = `container_message` //創(chuàng)建虛擬節(jié)點(diǎn) const vm = createVNode( MessageConstructor, options, ) //渲染虛擬節(jié)點(diǎn) render(vm, container) document.body.appendChild(container);} export default { //組件祖冊(cè) install(app: App): void { app.config.globalProperties.$message = Message }}
插件封裝完整地址。源碼位置————packages/runtime-core/src/apiCreateApp中的createAppAPI函數(shù)中的mount方法。
以上就是vue3.0實(shí)現(xiàn)插件封裝的詳細(xì)內(nèi)容,更多關(guān)于vue 插件封裝的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. SpringBoot項(xiàng)目?jī)?yōu)雅的全局異常處理方式(全網(wǎng)最新)2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. 解決python路徑錯(cuò)誤,運(yùn)行.py文件,找不到路徑的問(wèn)題4. Python TestSuite生成測(cè)試報(bào)告過(guò)程解析5. IntelliJ IDEA設(shè)置背景圖片的方法步驟6. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明7. docker /var/lib/docker/aufs/mnt 目錄清理方法8. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法9. Vue作用域插槽實(shí)現(xiàn)方法及作用詳解10. 如何清空python的變量
