VUE自定义吐司toast
程序员文章站
2024-03-05 10:58:00
...
一个在学习vue的小白,各种折腾,最近页面需要用到toast,故查了部分资料。
使用toast有两个方式,
一个是使用第三方插件(这个网上很多,大家可以自行搜索,上个链接供大家参考https://www.npmjs.com/package/vue2-toast);
另一个方式是自定义一个toast,效果见下图:
文件目录:
index.js文件代码:
import Vue from 'vue'
import toast from './toast.vue'
// 创建组件构造器
const toastHonor = Vue.extend(toast);
export default function ({text="要显示的内容",time=2000,type=undefined}={}) {
return new Promise((reslove, reject) => {
let toastComponent = new toastHonor({el: document.createElement('div')});
toastComponent.text = text;
toastComponent.time = time;
toastComponent.type = type;
//插入到body
document.body.appendChild(toastComponent.$el)
// 回调函数
toastComponent.close = function () {
reslove();
};
})
}
toast.vue组件代码:
<template>
<transition @before-leave="beforeLeave" @after-leave="afterLeave" name="slide-fade">
<div @click="hideToast" v-show="isShow" class="toast">
<div class="main">
<div v-if="type" class="icon-box" flex="main:center cross:center">
<i v-show="type==='succeed'" class="iconfont icon-ic_select_simple font30 orange2"></i>
</div>
<div class="text">
{{text}}
</div>
</div>
</div>
</transition>
</template>
<script>
export default {
props: {
text: {type: String},
time: {type: Number},
type: {type: String},
},
mounted() {
this.$nextTick(() => {
this.isShow = true;
this.timer = setTimeout(() => {
this.hideToast();
}, this.time)
});
},
data() {
return {
isShow: false,
timer: null,
};
},
methods: {
hideToast() {
this.isShow = false;
clearTimeout(this.timer);
this.timer = null;
},
beforeLeave() {
this.close();
},
afterLeave() {
document.body.removeChild(this.$el);
}
}
};
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
z-index: 9999;
}
.main {
display: inline-block;
padding: 0.5rem 1rem;
min-width: 10vm;
/*max-width: 4.4rem;*/
border-radius: .5rem;
background-color: rgba(66, 63, 56, 0.8);
}
.icon-box {
margin: 0 auto .1rem;
width: .7rem;
height: .7rem;
border-radius: 50%;
overflow: hidden;
background-color: #fff;
}
.text {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
font-size: 4vw;
/*line-height: 7.5vw;*/
color: #fff;
}
.slide-fade-enter-active {
transition: all 0.3s ease;
}
.slide-fade-leave-active {
transition: all 0.3s ease;
}
.slide-fade-enter {
transform: translate(-50%, -1.2rem);
opacity: 0;
}
.slide-fade-leave-to {
transform: translate(-50%, 0.5rem);
opacity: 0;
}
</style>
使用方式:
在组件中导入
import toast from "../../components/myToast/index.js";
组件代码--页面部分,一个按钮点击事件触发吐司:
<button @click="showToast">点击显示我的吐司</button>
事件调用方式:
methods:{
showToast(){
toast({text:"我是吐司,我显示3s",time:3000})
.then(()=>{
console.log("关闭后执行");
})
.catch(()=>{})
}
}
可以根据项目需求修改toast组件,达到项目要求。
大部分内容参考https://blog.csdn.net/weixin_37745920/article/details/101371944。大家可以参照。