当然,要想实现这种效果,方法有很多。
- 通过定义组件,先在
App.vue
里面放置,并通过改变全局变量进行控制- 通过
Vue.extend
创建构造器,手动把组件挂载到DOM上去
这里只是简单告诉了你们如何使用,更多功能可以根据需求自己定义
🚀💨
Toast组件目录
image.png这篇文章主要是通过
Vue.extend
的方法
main.js中引入
import Toast from './components/Toast'
Vue.prototype.$toast = Toast //挂载到vue原型上
main.vue
<template>
<transition name="fade">
<div id="toast" v-if="visible">
<div class="toast">{{message}}</div>
</div>
</transition>
</template>
<script>
export default {
watch: {
closed(val) {
if (val) {
this.visible = false;
// this.destroyElement();
}
}
},
data() {
return {
visible: false,
message: "",
duration: 3, // 显示时长,秒
closed: false, // 用来判断消息框是否关闭
timer: null // 计时器
};
},
mounted() {
this.startTimer();
},
methods: {
//完全销毁实例
destroyElement() {
// https://cn.vuejs.org/v2/api/#vm-destroy
this.$destroy();
this.$el.parentNode.removeChild(this.$el);
},
//计时器,根据 duration 去修改组件的开关状态
startTimer() {
this.timer = setTimeout(() => {
if (!this.closed) {
this.closed = true;
clearTimeout(this.timer);
}
}, this.duration * 1000);
}
}
};
</script>
<style lang="scss" scoped>
#toast {
z-index: 9999;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.toast {
display: inline-block;
max-width: 80vw;
background: rgba(24, 151, 119, 0.63);
padding: 0.5rem 1rem;
text-align: center;
color: white;
font-size: 14px;
}
}
.fade-enter-active {
animation: fade 1s;
}
.fade-leave-active {
animation: fade 1s reverse;
}
@keyframes fade {
0% {
transform: scale(1) translateX(200px);
opacity: 0;
}
100% {
transform: scale(1) translateX(0);
opacity: 1;
}
}
</style>
index.js
import Vue from 'vue';
import Main from './main.vue'
// https://cn.vuejs.org/v2/api/#Vue-extend
// 创建构造器
let ToastConstructor = Vue.extend(Main);
let instance
let seed = 1 // 计数
const Toast = (options = {}) => {
//判断如果传入的是一个字符串,那么就使用message提示
if (typeof options === 'string') {
options = {
message: options
}
}
let id = `toast_${seed++}`
instance = new ToastConstructor({
data: options
})// 创建对象实例
instance.id = id
// https://cn.vuejs.org/v2/api/#vm-mount
// 手动挂载一个实例并插入到 body 中
instance.$mount()
document.body.appendChild(instance.$el)
instance.visible = true
return instance
}
export default Toast
使用
this.$toast("我是一个Toast轻提示");
or
this.$toast({ message: "我是一个Toast轻提示", duration: 2 });
网友评论