Vue插件(plugin)听起来很高大上,平时都是使用别人写的,那如果要自己实现一个呢,现在就用一个小demo来尝试一把,完成后会发现插件其实也没那么高大上嘛,废话不多说,直接上代码!
以下代码为了方便测试,会直接在一个HTML里面呈现,并且以cdn的方式引入vue.js
-
准备工作:
1、在页面引入vue.js
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
2、加上css
<style> *{ padding: 0; margin: 0; } .popup{ position: fixed; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, .5); z-index: 100; display: flex; justify-content: center; align-items: center; } .popup-inner{ width: 280px; height: 160px; background: #1f2a3e; position: relative; font-size: 14px; } .popup-title{ height: 38px; line-height: 38px; background: #101624; color: #4a516b; font-size: 16px; text-indent: 10px; font-weight: normal; } .popup-close{ position: absolute; top:6px; right: 10px; color: #a7b6e1; font-weight: bold; font-size: 16px; cursor: pointer; } .popup-content{ color: #a3b9f2; text-align: center; margin: 24px 0 20px; } .popup-button{ text-align: center; } .popup-button input[type=button]{ width: 78px; height: 22px; border: 1px solid #f8ecb2; line-height: 24px; color: #6a3e00; background: #fac430; border-radius: 2px; } </style>
3、HTML
<div id="app"> <button @click="showMsg">点击显示</button> </div>
代码核心:
<!-- 弹窗组件模板 --> <script type="text/x-template" id="popup"> <div class="popup" v-show="isShow"> <div class="popup-inner"> <h2 class="popup-title">{{ this.title || '操作提示' }}</h2> <a class="popup-close" title="点击关闭" @click="popupClose">X</a> <div class="popup-main"> <div class="popup-content"> <slot></slot> </div> <div class="popup-button"><input type="button" value="确定" @click="popupClose"></div> </div> </div> </div> </script> <script type="text/javascript"> //第1步:创建弹窗组件 let popupComp = Vue.component('popup-comp', { template: '#popup', props: { isShow: { type: Boolean, required: true }, title:{ type: String, required: false, } }, methods: { popupClose(){ this.$emit('close') } }, }) //第2步:使用基础Vue构造器,创建一个弹窗子类,里面的选项即为组件选项,或者一个.vue组件 var popup = Vue.extend(popupComp) //第3步:实例化弹窗组件,并挂载到Dom function alert(title, msg, callback) { //实例化弹窗子类 var popupVm = new popup({ propsData: { isShow : true, title : title } }); //指定弹窗默认插槽的内容 popupVm.$slots.default = [msg] var popupEl = document.createElement("div"); document.body.appendChild(popupEl); popupVm.$mount(popupEl) //挂载到元素 //定义关闭事件,在弹窗子类里面触发 popupVm.$on("close", ()=>{ popupVm.isShow = false popupVm.$nextTick(()=>{ popupVm.$destroy() popupEl.remove() }) if(callback) callback() }) } //第4步:注册插件,添加实例方法 var popupPlugin = {} popupPlugin.install = function (Vue,options) { Vue.prototype.$alert = function (title, msg, callback) { alert(title, msg, callback) } } //第5步:使用插件 Vue.use(popupPlugin) //最后:整个程序入口,使用插件的实例方法 new Vue({ el:'#app', methods: { showMsg(){ //alert(null,'操作失败,请稍后重试') this.$alert('操作提示','操作失败,请稍后重试') } }, }) </script>
最终效果:点击按钮时会弹窗,并且可以随时随地的调用,因为已经注册到全局了