自定义alert弹窗

2019-05-30  本文已影响0人  jumper996

1. 效果

image.png

2. 调用方式

this.$alert({
      message: '自定义消息',
      btn: '自定义按钮',
      click: function () {
        console.log('自定义事件')
      }
 })

3.创建Alert.vue组件

<style scoped>
  .mask {
    top: 0;
    left: 0;
    position: fixed;
    width: 100vw;
    height: 100vh;
    z-index: 1000;
    background: black;
    opacity: 0.7;
  }
  .sy-alert {
    border-radius: 5px;
    width: 230px;
    height: 140px;
    background: white;
    z-index: 1001;
    left: calc(50vw - 115px);
    position: absolute;
  }
  .sy-alert .top {
    box-sizing: border-box;
    font-size: 15px;
    color: #9f9f9f;
    width: 100%;
    height: 70%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
  }

  .sy-alert .bottom {
    font-size: 18px;
    color: #00c200;
    border-top: 1px solid #e6e7e8;
    width: 100%;
    height: 30%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: white;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  .sy-alert .bottom:active {
    opacity: 0.7;
    background: #e6e7e8 ;
  }
</style>
<template>
  <div v-if="visible" class="alert-content">
    <div class="mask" >

    </div>
    <div class="sy-alert" :style="{ 'top': positionTop}">
      <div class="top"><div>{{message}}</div></div>
      <div class="bottom" @click="closeAlert()">{{btn}}</div>
    </div>
  </div>
</template>

<script>

export default {
  props: [
    'positionTop',
    'btn',
    'message'
  ],
  data () {
    return {
      visible: false
    }
  }
}
</script>

4.创建Alert构造js

import Alert from '../components/Alert'
import Vue from 'vue'

const AlertConstructor = Vue.extend(Alert)
const alert = (opts = {}) => {
  let _a = new AlertConstructor({el: document.createElement('div')})
  _a.message = opts.message || '消息啊'
  _a.btn = opts.btn || '按钮啊'
  _a.positionTop = opts.positionTop || 100 + 'px'
  _a.visible = true
  opts.click = opts.click || function () {
    console.log('点击了取消')
  }
  document.body.appendChild(_a.$el)
  return new Promise(resolve => {
    return (
      _a.closeAlert = () => {
        _a.visible = false
        opts.click()
        resolve()
      })
  })
}
export default alert

5.main.js中Vue设置全局变量

import Vue from 'vue'
import Alert from './build/alert'
Vue.prototype.$alert = Alert

参考:https://www.jianshu.com/p/44db3c29cb3e

上一篇下一篇

猜你喜欢

热点阅读