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>
最終效果:點擊按鈕時會彈窗,並且可以隨時隨地的調用,因為已經注冊到全局了