OK,首先看看效果:
一、子组件(alert.vue)
<template> <transition name="alert"> <div class="alert-all"> <div class="alert-wraper determine"> <p class="close-alert"> <!-- <i class="fa fa-times" aria-hidden="true" title="关闭" @click="close()"></i> --> </p> <p :class="[{fail: ifFail}, 'title']">{{title}}</p> <div class="btn_wrapper"> <!--<div class="cancel" @click="ok(false)">取消</div>--> <div class="ok" @click="ok(true)">确定</div> </div> </div> </div> </transition> </template> <script> export default { name: 'alert', props: { title: { type: String, default () { return {} } }, type: { type: String, default () { return {} } }, autoHide: { type: Boolean, default () { return true } } }, data () { return { ifFail: '' } }, methods: { ok: function (flag) { let data = { show: flag, type: this.type } this.$emit('okAlert', data) } }, mounted () { if (this.type === 'fail') { this.ifFail = true } else { this.ifFail = false } } } </script> <style lang="less" scoped> .alert-all{ position:fixed; 100%; height:100%; top:0; left:0; z-index:9; .alert-wraper{ 400px; height:160px; background:#fff; position:absolute; top:0; left:0; right:0; bottom:0; margin:auto; box-shadow:0px 0px 20px #ddd; .close-alert{ height:30px; height:30px; 100%; background:#4499ee; position:relative; z-index:9; i{ position:absolute; right:0; 30px; height:30px; font-size: 20px; cursor:pointer; color:#fff; } i::before{ position:absolute; left:6px; top:4px; } i:hover{ background:#6db2f8; } } .fail{ color:red; } .title{ box-sizing: border-box; padding: 0 10px; 100%; height:130px; line-height: 25px; font-size:14px; font-weight: normal; text-align:center; display: flex; justify-content: center; align-items: center; } } .determine{ height: 220px; } .btn_wrapper{ text-align: center; } .cancel, .ok{ display: inline-block; 80px; height: 30px; border-radius: 20px; border: 1px solid #4499ee; text-align: center; line-height: 30px; color: #4499ee; margin:0 20px; } .cancel:hover, .ok:hover{ cursor: pointer; box-shadow: 0 0 4px #4499ee; } } .alert-enter-active,.alert-leave-active{ transition: all .4s } .alert-enter, .alert-leave-to{ opacity: 0; transform: translateY(-60px); } </style>
二、父组件中引用子组件(alert.vue)
<template> <div class="container"> <alerter v-if="alertManager.show" :type="alertManager.type" :title="alertManager.title"> </alerter> </div> </template>
三、父组件中定义变量
export default {
data () {
return {
alertManager: {
show: false,
type: '',
title: ''
}
}
}
四、父组件中写弹出框方法
methods: {
alert (show, type, title, autoHide) {
this.alertManager = {
show: show,
type: type,
title: title
}
if (autoHide === true) {
let that = this
setTimeout(function () {
that.alertManager.show = false
}, 2000)
}
}
}
五、调用方法
that.alert(true, 'success', '提交成功', true)