定义样式 sass
.toast-container
position: absolute
top: 45%
left: 50%
transform: translate(-50%, -50%)
width: 80%
height: auto
padding: 20px
background-color: #333
border-radius: 5px
box-shadow: 0 0 10px rgba(0, 0, 0, .4)
text-align: center
font-size: 14px
transition: opacity .3s
&.fade-out
opacity: 0
定义js
import '@/assets/style/toast.sass';
function Toast (str, options = {}) {
let { time, html } = options;
if (!time) time = 1200;
const toastEl = document.createElement('div');
const className = 'toast-container';
toastEl.className = className;
if (html) {
toastEl.innerHTML = str;
} else {
if (toastEl.textContent) {
toastEl.textContent = str;
} else {
toastEl.innerText = str;
}
}
document.body.appendChild(toastEl);
setTimeout(() => {
toastEl.className = className + ' fade-out';
setTimeout(() => {
document.body.removeChild(toastEl);
}, 300);
}, time);
}
导出
export default Toast;
使用
在main.js里面引入
import toast from '@/自己的路径/toast.js';
挂载到原型上
Vue.prototype.toast = toast;
在页面里面使用
this.toast('字符串',{time:"时间",html:"html模板或者是文本"})