vue3 全局弹窗组件编写

弹窗示例 弹窗示例
alert1
alert2
alert3
alert4
  1. 用命令行npm init vue@latest新建的项目,并运行起来
  2. components文件夹下新建一个文件夹hl-alert,该文件夹下新增hl-alert.vue和index.js文件,目录结构如下图


    目录结构

    2.1 hl-alet.vue文件中定义传入组件的属性和方法,内容如下:

<template>
  <div class="base-alert" ref="hlAlert">
    <div class="base-alert-bg"></div>
    <div class="m-pop-content">
      <img src="~@/assets/close.png" alt="" class="m-pop-close" v-if="isCloseIcon" @click="handleCancel"/>
      <div class="m-pop-title" v-html="title" v-if="title"></div>
      <div class="m-pop-detail">
        <div v-html="message" v-if="message" class="m-pop-message"></div>
        <div v-html="subMessage" v-if="subMessage" class="m-pop-submessage"></div>
      </div>
      <div class="g-row-flex-right g-btn-group">
        <button :class="['u-base-pop-cancel', cancelBtnClass]" @click="handleCancel" v-if="!hideCancel">{{cancelBtnText}}</button>
        <button class="u-base-pop-create" @click="handleOk">{{ensureBtnText}}</button>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from 'vue'
export default defineComponent({
  name: 'HlAlert',
  props: {
    title: {
      type: String,
      default: '信息提示',
    },
    message: {
      type: String,
      default: '',
    },
    subMessage: {
      type: String,
      default: '',
    },
    cancelBtnClass: {
      type: String,
      default: '',
    },
    ensureBtnText: {
      type: String,
      default: '确定',
    },
    cancelBtnText: {
      type: String,
      default: '取消',
    },
    isCloseIcon: {
      type: Boolean,
      default: false,
    },
    callback: {
      type: Function,
    },
    callbackCancel: {
      type: Function,
    },
    hideCancel: {
      type: Boolean,
      default: false,
    },
    closeFromWindowClick: {
      type: Boolean,
      default: true
    }
  },
  setup (props) {
    const hlAlert = ref(null)
    function removeModal () {
      props.closeFromWindowClick && window.removeEventListener('click', removeModal)
      let parent = (hlAlert.value && (hlAlert.value).parentNode) || null
      if (hlAlert.value && document.body.contains(parent)) {
        document.body.removeChild(parent)
      }
    }
    function handleCancel () {
      removeModal()
      props.callbackCancel && props.callbackCancel()
    }
    function handleOk () {
      removeModal()
      props.callback && props.callback()
    }
    onMounted(() => {
      setTimeout(() => {
        props.closeFromWindowClick && window.addEventListener('click', removeModal)
      }, 100)
    })
    return {
      hlAlert,
      handleOk,
      handleCancel
    }
  }
})
</script>

<style lang="scss">
  @mixin box-sizing($value) {
    box-sizing: $value;
    -webkit-box-sizing: $value;
    -o-box-sizing: $value;
    -moz-box-sizing: $value;
  }

  @mixin box($w, $h) {
    height: $h;
    width: $w;
    padding: 0;
    box-sizing: border-box;
    @include box-sizing(border-box);
  }
  .base-alert {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    @include box(100%, 100%);
    top: 0;
    left: 0;
    z-index: 2;
    .g-row-flex-right {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .m-pop-close {
      position: absolute;
      right: 16px;
      top: 16px;
      cursor: pointer;
      z-index: 2;
    }
    .m-pop-title {
      font-size: 15px;
      font-weight: 500;
      color: #5A6371;
      text-indent: 24px;
      line-height: 40px;
      padding-top: 10px;
    }
    .m-pop-content {
      @include box(auto, auto);
      min-width: 372px;
      min-height: 156px;
      background: #fff;
      z-index: 1;
      box-shadow: 3px 5px 21px 0px rgba(183, 183, 183, 0.29);
      border: 1px solid #EBEBEB;
      padding-bottom: 24px;
      position: relative;
      border-radius: 8px;
    }
    .base-alert-bg {
      position: fixed;
      @include box(100%, 100%);
      top: 0;
      left: 0;
    }
    .m-pop-detail {
      padding-top: 32px;
    }
    .m-pop-message {
      text-align: center;
      font-size: 14px;
      font-weight: bold;
      color: #737478;
      margin-bottom: 5px;
    }
    .m-pop-submessage {
      font-size: 14px;
      font-weight: 400;
      color: #5A6371;
      text-align: left;
      padding-left: 40px;
      max-width: 372px;
      margin: auto;
    }
    .g-edit-list {
      margin-bottom: 16px;
    }
    .g-btn-group {
      margin-top: 30px;
      padding-right: 16px;
    }
    .g-message-info {
      font-size: 14px;
      font-weight: 400;
      text-align: center;
    }
    // 按钮样式
    .u-base-pop-create,
    .u-base-pop-cancel {
      @include box(90px, 32px);
      cursor: pointer;
      border: none;
      outline: none;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #EFF7FF;
      font-size: 14px;
      font-weight: 500;
      border-radius: 4px;
    }
    .u-base-pop-create {
      background: #536FFF;
    }
    .u-base-pop-cancel {
      background-color: #fff;
      border: 1px solid;
      color: #2F51FF;
      border-color: #536FFF;
      margin-right: 20px;
      margin-bottom: 0;
    }
  }
</style>

2.2 vue2移除了vue.extend,我们使用createVNode和render来渲染弹窗
然后挂载到 config.globalProperties 上
index.js内容如下:

import {createVNode, render} from 'vue'
import HlAlert from './hl-alert.vue'

const myAlert = function(options) {
    const container = document.createElement('div')
    const vm = createVNode(
      HlAlert,
      options
    )
    render(vm, container)
    document.body.appendChild(container)
}  
const MyHlAlert = {
  install(app) {
    // 配置此应用
    app.config.globalProperties.$hlAlert = myAlert
  }
}
export default MyHlAlert
  1. main.js中引入弹窗组件
import { createApp } from 'vue'
import App from './App.vue'
import HlAlert from './components/hl-alert/index'

import './assets/main.css'
const app = createApp(App)
app.use(HlAlert)
app.mount('#app')
  1. 页面中使用
<script setup>
  import {getCurrentInstance} from 'vue'
  const {appContext} = getCurrentInstance()
  const globalProxy = appContext.config.globalProperties  
  function alert () {
    globalProxy.$hlAlert({
      title: '审核未通过原因',
      subMessage: '审核未通审核未通审核未通审核未通审核未通',
      isCloseIcon: true,
      cancelBtnClass: 'm-red', // 取消按钮的class
      callback: () => {
        console.log('确定按钮')
      }
    })
  }
  function alert2 () {
    globalProxy.$hlAlert({
      title: '信息提示',
      subMessage: '只展示一个按钮',
      isCloseIcon: true,
      ensureBtnText: '确定', // 确认按钮的文字
      cancelBtnText: '取消', // 取消按钮的文字
      hideCancel: true // true 隐藏取消按钮
    })
  }
  function alert3 () {
    globalProxy.$hlAlert({
      title: '信息提示',
      subMessage: '确定按钮文字修改',
      isCloseIcon: true,
      ensureBtnText: '知道了', // 确认按钮的文字
      cancelBtnText: '取消', // 取消按钮的文字
      hideCancel: true // true 隐藏取消按钮
    })
  }
  function alert4 () {
    globalProxy.$hlAlert({
      title: '信息提示',
      subMessage: '<p style="text-align: left;color: red;">审核未通审核未通审核未通审核未通审核未通</p>',
      isCloseIcon: true,
      cancelBtnClass: 'm-red', // 取消按钮的class
      callback: () => {
        console.log('确定按钮')
      }
    })
  }
</script>

<template>
  <div>
    <button @click="alert">click1</button>
    <button @click="alert2">click2</button>
    <button @click="alert3">click3</button>
    <button @click="alert4">click4</button>
  </div>
</template>

<style lang="scss">
.base-alert .m-red {
  border: 1px solid #536FFF;
  background: transparent;
  color: #536FFF;
  margin-right: 16px;
}
</style>
  1. 如果想把该组件发布到npm上,请参考文章 npm 发布自己写的vue3的组件
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容