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. 基于PHP做個(gè)圖片防盜鏈2. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)3. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)4. XML在語(yǔ)音合成中的應(yīng)用5. jscript與vbscript 操作XML元素屬性的代碼6. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解7. ASP.NET MVC把數(shù)據(jù)庫(kù)中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字8. 如何使用ASP.NET Core 配置文件9. .NET中實(shí)現(xiàn)對(duì)象數(shù)據(jù)映射示例詳解10. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車(chē)輛管理系統(tǒng)
