vue3.0實現插件封裝
最近公司有一個新的項目,項目框架是我來負責搭建的,所以果斷選擇了Vue3.x+ts。vue3.x不同于vue2.x,他們兩的插件封裝方式完全不一樣。由于項目中需要用到自定義提示框,所以想著自己封裝一個。vue2.x提供了一個vue.extend的全局方法。那么vue3.x是不是也會提供什么方法呢?果然從vue3.x源碼中還是找到了。插件封裝的方法,還是分為兩步。
1、組件準備按照vue3.x的組件風格封裝一個自定義提示框組件。在props屬性中定義好。需要傳入的數據流。
<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、插件注冊
這個才是插件封裝的重點。不過代碼量非常少,只有那么核心的幾行。主要是調用了vue3.x中的createVNode創建虛擬節點,然后調用render方法將虛擬節點渲染成真實節點。并掛在到真實節點上。本質上就是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` //創建虛擬節點 const vm = createVNode( MessageConstructor, options, ) //渲染虛擬節點 render(vm, container) document.body.appendChild(container);} export default { //組件祖冊 install(app: App): void { app.config.globalProperties.$message = Message }}
插件封裝完整地址。源碼位置————packages/runtime-core/src/apiCreateApp中的createAppAPI函數中的mount方法。
以上就是vue3.0實現插件封裝的詳細內容,更多關于vue 插件封裝的資料請關注好吧啦網其它相關文章!
相關文章:
