Vue实现全局的toast组件方式
短信预约 -IT技能 免费直播动态提醒
Vue全局的toast组件
1.创建toast组件
<template>
<div class="toast" v-if="show">
{{ msg }}
</div>
</template>
<style scoped>
.toast{
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
border-radius: 3px;
max-width: 200px;
padding: 10px;
background: #333;
color: #fff;
font-size: 14px;
opacity: .9;
text-align: justify;
word-break: break-all;
word-wrap: break-word;
}
</style>
2.创建toast.js文件
import toast from "@/components/toast"
export default (Vue) => {
let toastComp = Vue.extend(toast);
function showToast(msg , duration = 3e3){
let toastDom = new toastComp({
data(){
return{
show:true,
msg
}
}
}).$mount()
document.body.appendChild(toastDom.$el);
setTimeout(() => {
toastDom.show = false
}, duration)
}
Vue.prototype.$toast = showToast;
}
3.安装并使用
import toast from "@/plugins/toast";
Vue.use(toast);
// 组件里面使用
this.$toast("message");
vue自定义toast组件
//toast.js
const TOAST_CLASS = 'toast'
const TOAST_OUT_CLASS = 'toast out'
let innerHtml=""
function toast(msg,time=1000) {
let body=document.querySelector('#app');
if(body.querySelector('.toast')){
body.removeChild(body.querySelector('.toast'))
}
let toastElem = document.createElement('div')
toastElem.setAttribute('class',TOAST_CLASS)
innerHtml = `<sapn>${msg}</sapn>`
toastElem.innerHTML = innerHtml;
body.appendChild(toastElem);
setTimeout(function () {
toastElem.setAttribute('class',TOAST_OUT_CLASS)
},time)
setTimeout(function () {
let elm = body.querySelector('.toast');
if(elm){
body.removeChild(elm)
}
},time+1000)
}
export default toast
//toast.less
@-webkit-keyframes toastIn {
0%{
opacity: 1;
}
50%{
opacity: 1;
}
100%{
opacity: 1;
}
}
@-webkit-keyframes toastOut {
0%{
opacity:1;
}
50%{
opacity:0.7;
}
100%{
opacity:0;
}
}
//animation: name duration timing-function delay iteration-count direction;
.toast{
position: fixed;
z-index:99;
background-color: rgba(0,0,0,0.6);
color:#fff;
padding:15px 25px;
border-radius:5px;
top: 50%;
left:50%;
font-size:18px;
transform: translate(-50% , -50%);
animation-name: toastIn;
animation-duration: 1s;
animation-iteration-count: 1;
animation-delay: 0s;
}
.toast.out {
animation-name: toastOut;
animation-duration: 1s;
animation-iteration-count: 1;
animation-delay: 0s;
animation-fill-mode: forwards;
}
使用
全局注入(main.js),this._toast(‘XXXX’)调用
import toast from "./utils/toast";
window._toast = toast
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341