Vue自定义全局弹窗组件

前言

页面中会有很多时候需要弹窗提示,我们可以写一个弹窗组件,但是如果每个页面都引入这个组件,太麻烦了,所以我们将它变成全局组件,需要用的时候直接通过JS调用即可,不需要在每个页面引入了

效果图

弹窗组件

在components目录下新建popup文件夹,然后在里面建立index.vue文件和index.js文件

弹窗的组件——index.vue

<template>

  <transition-group name='fade'>
    <!-- 蒙版 -->
    <div class="mask"
         key="1"
         @click="show = false"
         v-if="show"
         @touchmove.prevent>

    </div>
    <div class="pop"
         v-show="show"
         key="2">
      <img :src="imgUrl"
           :alt="imgLoadTip">
      <h1>{{title}}</h1>
      <p>{{content}}</p>
      <button @click="btnClick">{{btnText}}</button>
      <img @click="show = false"
           class="close"
           src="../assets/imgs/clear.png"
           alt="">
    </div>

  </transition-group>

</template>

 

<script>
export default {
  name: 'Popup',
  data() {
    return {
      show: false,
      imgUrl: '',
      title: '',
      content: '',
      btnText: '',
    }
  },
  created() {},
  methods: {
    btnClick() {
      this.click()
      this.show = false
    },
  },
}
</script>

 

<style lang="less" scoped>
// 渐变过渡
.fade-enter,
.fade-leave-active {
  opacity: 0;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.35s;
}
// 全局弹窗
.mask {
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  z-index: 10;
  width: 100%;
  height: 100%;
}

.pop {
  height: 300px;
  width: 80%;
  background: #fff;
  border-radius: 8px;
  position: fixed;
  top: 100px;
  left: 50%;
  margin-left: -40%;
  z-index: 20;
  text-align: center;

  button {
    background: #f95644;
    border-radius: 32px;
    width: 180px;
    height: 50px;
    font-size: 18px;
    color: #ffffff;
  }
  .close {
    top: 0;
    right: 10px;
    position: absolute;
    display: block;
    width: 40px;
    height: 40px;
  }
}
</style>

 

index.js文件,写方法

import Vue from 'vue'
import Popup from './index.vue'

const PopupBox = Vue.extend(Popup)

Popup.install = function (data) {
  let instance = new PopupBox({
    data
  }).$mount()

  document.body.appendChild(instance.$el)

  Vue.nextTick(() => {
    instance.show = true
    // show 和弹窗组件里的show对应,用于控制显隐
  })
}

export default Popup

main.js引入vue组件

 import Popup from "./components/popup/index"
 Vue.prototype.$popup = Popup.install

组件中使用方法

   btnClick() {
      this.$popup({
        imgUrl: require('../assets/imgs/test_result.png'), // 顶部图片
        imgLoadTip:'图片加载中...',
        title: '我是标题',
        content: '我是内容',
        btnText: '我是按钮',
        click: () => {
          // 点击按钮事件
          //   this.$router.push('……')
          console.log(`点击按钮了!`)
        },
      })
    },

 至此,一个全局弹框组件就完成 了!

posted @ 2020-08-13 17:39  Fanyee  阅读(3243)  评论(0编辑  收藏  举报