如何配置消息卡片(分享基于Vue做一个消息通知组件)

常见问题 2022-07-26 16:38:40 阅读:172

今天除夕,在这里祝大家新年快乐!!!今天在这个特别的日子里我们做一个消息通知组件,好,我们开始行动起来吧!!!
项目一览
效果很简单,就是这种的小卡片似的效果。

我们先开始写UI页面,可自定义消息内容以及关闭按钮的样式。
Notification.vue
<template>
<transition name="fade" @after-enter="handleAfterEnter">
<div :style="style" v-show="visible">
<span>
{{content}}
</span>
<span @click="handleClose">{{btn}}</span>
</div>
</transition>
</template>
<script>
export default {
name: 'Notification',
props: {
content: {
type: String,
required: true
},
btn: {
type: String,
default: 'close'
}
}
}
</script>
<style scoped>
.fade-enter-active, .fade-leave-active{
transition: opacity 1s;
}
.fade-enter, .fade-leave-to{
opacity: 0;
transform: translateX(100px);
}
.notification{
display: flex;
background-color: #303030;
color: rgba(255, 255, 255, 1);
align-items: center;
padding: 20px;
position: fixed;
min-width: 280px;
box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.3);
flex-wrap: wrap;
transition: all 0.3s;
border-radius:10px ;
&__content{
padding: 0;
}
&__btn{
color: #ff4081;
padding-left: 24px;
margin-left: auto;
cursor: pointer;
}
}
</style>
写完基本的样式组件,我们该赋予其灵魂了。好,我们开始写最重要的逻辑。
notify.js
import Vue from "vue";
import Notification from "./Notification.vue";
const NotificationConstructor = Vue.extend(Notification);
const instances = [];
let seed = 1;
// 消除Vue实例
const removeInstance = (instance) => {
if (!instance) return;
const len = instances.length;
const index = instances.findIndex((ins) => instance.id === ins.id);
instances.splice(index, 1);
if (len <= 1) return;
const removeHeight = instance.height;
for (let i = index; i < len - 1; i++) {
instances[i].verticalOffset =
parseInt(instances[i].verticalOffset) - removeHeight - 16;
}
};
const notify = (options = {}) => {
if (Vue.prototype.$isServer) return;
// 获取vue实例
let instance = new NotificationConstructor({
propsData: options, // 这里是传进来一组props
data() {
return {
verticalOffset: 0,
timer: null,
visible: false,
height: 0,
};
},
computed: {
// 配置消息组件的位置
style() {
return {
position: "fixed",
right: "20px",
bottom: `${this.verticalOffset}px`,
};
}
},
mounted() {
this.createTimer();
this.$el.addEventListener("mouseenter", () => {
if (this.timer) {
this.clearTimer(this.timer);
}
});
this.$el.addEventListener("mouseleave", () => {
if (this.timer) {
this.clearTimer(this.timer);
}
this.createTimer();
});
},
updated() {
this.height = this.$el.offsetHeight;
},


相关推荐

热门文章

立即加入,领取您的专属解决方案

电话咨询免费试用