1、创建myMsg文件夹 目录结构如下
2、 myNotify.vue
<!-- myNotify.vue -->
<template>
<transition name="slide-fade">
<div class="my-notify" v-if="notifyFlag">
<div class="notify success" v-if="type == 'success'">
<!-- <span>成功</span> -->
<div class="content">{{ content }}</div>
</div>
<div class="notify error" v-else-if="type == 'error'">
<!-- <span>错误</span> -->
<div class="content">{{ content }}</div>
</div>
<div class="notify warning" v-else-if="type == 'warning'">
<!-- <span>警告</span> -->
<div class="content">{{ content }}</div>
</div>
</div>
</transition>
</template>
<style scoped lang="scss">
.slide-fade-leave-active {
transition: all 0.3s translateY(-10px);
}
.slide-fade-enter,
.slide-fade-leave-to {
transform: translateX(10px);
opacity: 0;
}
.notify {
position: fixed;
right: 0;
top: 0;
width: 100%;
height: 40px;
border-radius: 0 0 10px 10px;
text-align: center;
color: #fff;
line-height: 40px;
font-size: 18px;
/* animation: show cubic-bezier(0.18, 0.89, 0.32, 1.28) 0.4s; */
}
.success {
background: $success-color;
}
.error {
background: $danger-color;
}
.warning {
background: #e0bb37;
}
.notify .content {
width: 100%;
}
@keyframes show {
0% {
right: -350px;
}
100% {
right: 10px;
}
}
</style>
3、index.js
import vue from "vue";
import myNotify from "./myNotify";
// 创建vue组件实例
const notify = vue.extend(myNotify);
//添加通知节点(用来存放通知的元素)
let notifyWrap = document.createElement("div");
// notifyWrap.className = "notify-wrap";
// notifyWrap.style =
// "position: fixed; right: 0px; top: 90px; transition-duration: .5s;";
document.body.appendChild(notifyWrap);
let myMsg = {
/**
* 通知框
* @content 提示内容;
* @type 提示框类型,parameter: success,error,warning
* @time 显示时长
*/
notify: ({ message, type, time = 1500 }) => {
//创建一个存放通知的div
const notifyDom = new notify({
el: document.createElement("div"),
data() {
return {
notifyFlag: true, // 是否显示
time: time, //提示框显示时长
content: message, // 文本内容
type: type, // 类型
timer: "", //定时器
timeFlag: false, // 是否显示
};
},
watch: {
timeFlag() {
if (this.timeFlag) {
this.notifyFlag = false;
window.clearTimeout(this.timer);
}
},
},
created() {
this.timer = setTimeout(() => {
this.timeFlag = true;
}, this.time);
},
beforeDestroy() {
window.clearTimeout(this.timer);
},
});
//往notifyWrap里面添加通知
notifyWrap.appendChild(notifyDom.$el);
},
};
// //注册
// function register() {
// vue.prototype.$myMsg = myMsg;
// }
export default myMsg;
4、使用
main.js
import Vue from "vue";
import App from "./App.vue";
import myMsg from "@/components/myMsg/index";
Vue.prototype.msgPrimary = function (msg) {
return myMsg.notify({ message: msg, type: "success" });
};
Vue.prototype.msgError = function (msg) {
return myMsg.notify({ message: msg, type: "error" });
};
Vue.prototype.msgWarning = function (msg) {
return myMsg.notify({ message: msg, type: "warning" });
};