vue自定义toast组件

本文介绍了如何在Vue中创建并使用自定义的Toast组件。通过引入toast.js和toast.less文件,然后在main.js中全局注册,即可在应用中通过this._toast('XXXX')方便地调用来显示提示信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值