1、场景
公司一直使用vue+element-ui来进行项目的开发,因此以前的信息提示弹出框一直使用element-ui的Message组件,然而,此次的项目拿到UI的设计图。
2、组件的创建
创建messageTips.vue文件,组件中代码如下:
<template>
<transition name="el-fade-in" >
<div class="mask" v-if="show">
<div class="message">
<div class="message-box">
<i class="message-icon" :class="'icon-'+type" ></i>
<span>{{message}}</span>
</div>
<a class="close" href="javascript:;" @click="close" >
</a>
</div>
</div>
</transition>
</template>
<script>
export default {
name: "MessageTips",
data() {
return {
message: "",
duration: 2000,
show: false,
type: "success",
timer: null
};
},
methods: {
close() {
this.timer = null;
this.show = false;
}
},
mounted() {
this.timer = setTimeout(() => {
this.show = false;
}, this.duration);
},
destroyed() {
this.timer = null;
}
};
</script>
<style lang="scss" scoped>
$success: #51d163;
$wt: #ffff;
$error: #ff4646;
.mask {
position: fixed;
width: 100vw;
height: 100vh;
top: 0;
right: 0;
background: rgba(0, 0, 0, 0.3);
.message {
width: 396px;
height: 160px;
position: absolute;
top: 15vh;
left: 0;
right: 0;
margin: auto;
box-sizing: border-box;
padding: 60px 0;
background: $wt;
&-box {
height: 40px;
text-align: center;
.message-icon {
display: inline-block;
width: 40px;
height: 40px;
box-sizing: border-box;
vertical-align: middle;
border-radius: 50%;
}
.icon-success {
border: 1px solid $success;
}
.icon-error {
background: url("./error_icon.png") no-repeat center;
}
span {
font: 700 16px/40px "";
padding-left: 12px;
}
}
.close {
width: 12px;
height: 12px;
position: absolute;
top: 20px;
right: 20px;
background: url("./close_icon.png") no-repeat center;
}
}
}
</style>
复制代码
给Vue的原型上添加$messageTips方法。
使用$mount挂在参数,并对参数进行判断,同时将组件插入页面中。新建messageTips.js文件代码如下,
import Vue from 'vue'
import MessageTips from './messageTips.vue'
Vue.prototype.$messageTips = (options) => {
//options为调用时的传入的参数
if (options === undefined) {
throw new Error('messageTips未传入提示信息')
} else if (typeof options === 'string' || typeof options === 'number') {
options = {
message: options
}
} else if (typeof options === 'object') {
options = options
}
let message = Vue.extend(MessageTips)
let component = new message({
data: options
}).$mount()
document.body.appendChild(component.$el)
Vue.nextTick(() => {
component.show = true
})
}
MessageTips.install = (vue) => {
vue.component(MessageTips.name, MessageTips)
}
export default MessageTips
复制代码
在main.js中引入并全局挂载
import MessageTips from '@/myComponents/MessageTips'
Vue.use(MessageTips)
复制代码
至此一个简单的信息提示弹出框组件已经创建完毕。
3、组件的使用
一个简单的使用测试如下: