提示的消息方法大概有两种:自定义弹框、原生弹框。显而易见自带的弹框的用户体验是很差的(尤其是再移动端),废话不多说,开始编写自定义我们的弹框吧~
功能分析:
通过封装 alert 可以封装成两种类型弹框:
结构**与样式如下:**
<template><div v-show="isShow"><div class="alert"><div class="flex">{{ msg }}</div><div v-if="type === 'alert'"><div class="btnCommon success" @click="close()">确定</div></div><div v-else class="space-round"><div class="btnCommon cancel" @click="cancelEvent()">取消</div><div class="btnCommon success" @click="successEvent()">确定</div></div></div><div class="mask" @click="closeMask()"></div></div></template><style lang="scss" scoped>$btn-main: #009688;$btn-dark: darken($btn-main, 5%);.alert {width: 300px;height: 150px;position: fixed;top: 50%;left: 50%;z-index: 300;border-radius: 6px;background-color: #fff;transform: translate(-50%, -50%);padding: 20px 10px;box-shadow: 0 5px 8px rgba(0, 0, 0, 0.05);display: flex;flex-flow: column nowrap;justify-content: center;align-items: center;}.flex {flex: 1;display: flex;align-items: center;}.space-round {display: flex;flex-flow: row nowrap;justify-content: space-around;align-items: center;width: 100%;padding: 0 10px;}.btnCommon {width: 105px;height: 32px;text-align: center;line-height: 32px;border-radius: 6px;cursor: pointer;&.success {color: #fff;background-color: $btn-main;&:hover {transition: 0.2s;background-color: $btn-dark;}}&.cancel {color: #333;background-color: #ededed;}}.mask {width: 100%;height: 100%;position: fixed;top: 0;left: 0;z-index: 299;background-color: rgba(0, 0, 0, 0.4);overflow: hidden;}</style>
逻辑(JS)部分如下:
export default {props: {type: {type: String,default: 'alert'},msg: {type: String,default: ''},isShow: {type: Boolean,default: false},success: {type: Function,default: () => {console.log('点击了success')}},cancel: {type: Function,default: () => console.log('点击了cancel')}},methods: {close() {// 通过原型链改变 isShow,将其隐藏window.vue.$alert('', false)},closeMask() {if (this.type === 'alert') {this.close()}},cancelEvent() {this.cancel()this.close()},successEvent() {this.success()this.close()}},mounted() {window.vue = this}}
开发插件:
import AlertComponent from './Alert.vue'const Alert = {}Alert.install = Vue => {// 创建一个具有 alert.vue 的 Vue构造器const AlertConstructor = Vue.extend(AlertComponent)const instance = new AlertConstructor()// 将实例挂载到一个新创建的 div 上instance.$mount(document.createElement('div'))// 插入到body的最下面document.body.appendChild(instance.$el)// 添加实例方法Vue.prototype.$alert = (msg, bol) => {instance.type = 'alert'instance.msg = msginstance.isShow = bol === undefined ? true : bol}Vue.prototype.$confirm = (msg, success, cancel, bol) => {instance.type = 'confirm'instance.msg = msginstance.isShow = bol === undefined ? true : bolif (typeof success !== 'undefined') {instance.success = success}if (typeof cancel !== 'undefined') {instance.cancel = cancel}}}export default Alert
全局使用插件:
// main.js...import Alert from './components/modules/alert'Vue.use(Alert)...
使用示例:
if (data.code === 500) {this.$alert('用户名密码校验失败,请检查!')} else {this.$alert('服务器错误!')}
