效果:在任意頁面,不需要引入組件,調用彈窗組件實例方法操作打開關閉
1. 定義
1.1 定義彈窗頁面
正常定義即可,需要定義方法show和hide控制組件變量顯示及隱藏彈窗。
1.2 彈窗頁面同級目錄定義得Vue需要得js文件
注意: 搞了單例,調用多少次都是操作一個
import Vue from 'vue' import FullLoginAd from './index.vue' // 單例模式 let instance = null function create (Component, props) { const vm = new Vue({ /* render函數用來生成虛擬dom,接收一個createElement函數(一般稱之h函數), 並返回該函數的執行結果(生成的虛擬dom)。 h函數接受三個參數, 1.一個標簽名或組件選項對象。 2.與模板中屬性對應的數據對象。 3.子節點。 生成的虛擬dom需要經過掛載($mount)才能變成真實dom */ render: h => h(Component, { props }) // 這里不指定宿主元素,因為直接指定body的話會將已有的內容替換掉。 }).$mount() /* 通過dom操作追加元素 $el可以獲取真實dom */ document.body.appendChild(vm.$el) /* 獲取組件實例 */ const comp = vm.$children[0] /* 添加銷毀組件的方法 */ comp.remove = function () { document.body.removeChild(vm.$el) vm.$destroy() } return comp } export default { /* install方法實現的需求是 在使用組件時不需要再傳入組件模板,只需傳入參數, 因此使用柯里化函數實現。*/ install(Vue) { Vue.prototype.$fullLoginAd = function(options) { if (!instance){ instance = create(FullLoginAd, options) } return instance } } }
// 綁定得組件實例,通過組件實例方法控制,傳遞方法傳參修改data里定義得內容
另一種寫法:
import FullLoginAd from '@/components/tencentAir/ads/FullLoginAd.vue'; export default { install(Vue){ // 生成一個Vue的子類 // 同時這個子類也就是組件 const FullLoginAdConstructor = Vue.extend(FullLoginAd) // 生成一個該子類的實例 const instance = new FullLoginAdConstructor(); // 將這個實例掛載在創建的div上 // 並將此div加入全局掛載點內部 instance.$mount(document.createElement('div')) document.body.appendChild(instance.$el) // 通過Vue的原型注冊一個方法 // 讓所有實例共享這個方法 Vue.prototype.$showFullLoginAd = (options) => { instance.showFlag = true; if (options){ for (let k in options){ instance[k] = options[k] } } } Vue.prototype.$hideFullLoginAd = () => { instance.showFlag = false; } } };
// 操作組件實例屬性控制,可控制props里得也可控制data里得
2. main.js使用
// 綁定到vue實例上創建登錄框
import FullLoginAd from '@/components/tencentAir/ads/FullLoginAd/index.js'
Vue.use(FullLoginAd)
3. 使用即可
// 創建實例,拿到實例對象,調用對象方法show
// 可以給show方法傳遞參數,達到彈窗動態展示數據得目的
this.$fullLoginAd().show()
this.$fullLoginAd().hide()
參考文章:
https://www.jianshu.com/p/9423f562c130