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(`點擊按鈕了!`)
        },
      })
    },

 至此,一個全局彈框組件就完成 了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM