vue全局弹窗

效果:在任意页面,不需要引入组件,调用弹窗组件实例方法操作打开关闭 

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

原文地址:https://www.cnblogs.com/zezhou/p/15594248.html