其他分享
首页 > 其他分享> > 利用Vue.extend生成全局弹窗

利用Vue.extend生成全局弹窗

作者:互联网

利用Vue.extend生成全局弹窗

效果

弹窗组件

<template>
  <div class="dialog" v-if="isVisible">
    <div class="mask" />
    <div class="info">
      <button @click="handleClose">关闭</button>
      <p>弹窗内容</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Dialog',
  data() {
    return {
      isVisible: false
    }
  },
  methods: {
    showDialog() {
      this.isVisible = true
    },
    handleClose() {
      this.isVisible = false
    }
  }
}
</script>

<style>
.mask {
  position: fixed;
  z-index: 1100;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: #000;
  opacity: .6;
}
.info {
  width: 600px;
  height: 700px;
  position: absolute;
  background-color: #fff;
  z-index: 1101;
}
</style>

Vue.extend创建ComponentConstructor

import Component from './dialog.vue'

Component.install = Vue => {
  const getInstance = (options) => {
    const ComponentConstructor = Vue.extend(Component)
    return new ComponentConstructor({
      el: document.createElement('div'),
      propsData: options
    })
  }

  Vue.prototype.$showDialog = (options) => {
    const instance = getInstance(options)
    document.body.appendChild(instance.$el)
    Vue.nextTick(() => {
      instance.showDialog()
    })
  }
}

export default Component

使用

import Vue from 'vue'
import Dialog from './components/index'

Vue.use(Dialog)

methods: {
  handleShowDialog() {
    this.$showDialog()
  }
}

标签:Vue,extend,Component,showDialog,options,弹窗
来源: https://www.cnblogs.com/chenfengami/p/14719555.html