1.在Vue里引入toast提示组件效果
2.重要代码片段
(1)html
<div class="npm-com-toast" v-show="isShow" @click="close">
<div class="mask">
<div class="box" @click.stop>
<div class="html" v-html="msg"></div>
</div>
</div>
</div>
(2)js
<script>
export default {
data () {
return {
msg: '',
isShow: false,
timeout: null,
resolve: null,
};
},
methods: {
/**
* 显示toast
* @desc 本方法为异步方法,将在toast关闭时执行成功回调
* @param {Number} [options.msg=''] 显示的内容,可以是html
* @param {Number} [options.duration=3000] 持续显示时间
*/
async show ({msg = '', duration = 3000} = {}) {
return new Promise(resolve => {
// 清除之前的Loading定时器
if (this.isShow) {
this.close();
}
this.msg = msg;
// 生成新的定时器
this.isShow = true;
this.resolve = resolve;
this.timeout = setTimeout(this.close, duration);
});
},
/**
* 关闭toast
* @param duration
*/
close () {
this.isShow = false;
clearTimeout(this.timeout);
this.timeout = null;
// 清空显示内容
this.msg = '';
if (this.resolve) {
this.resolve();
this.resolve = null;
}
},
/**
* 显示/关闭toast提示
* @desc 本方法为异步方法,将在toast关闭时执行成功回调
* @param {Object} options 复合参数(值为false:隐藏|值为其他情况或不传:显示)
* @param {Number} [options.duration=30000] 持续显示时间
*/
async toast (options) {
if (options === false) {
await this.close();
} else {
await this.show(options);
}
},
}
};
</script>
(3) css
.npm-com-toast {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: table;
z-index: 100;
line-height: 1;
.mask {
display: table-cell;
vertical-align: middle;
text-align: center;
animation: npm-com-toast-mask-animation 0.3s forwards;
@keyframes npm-com-toast-mask-animation {
0% {
background: rgba(0, 0, 0, 0);
}
100% {
background: rgba(0, 0, 0, 0.1);
}
}
.box {
display: inline-block;
box-sizing: border-box;
padding: 10px 15px;
min-width: 120px;
max-width: 120px;
min-height: 40px;
border-radius: 4px;
background: rgba(0, 0, 0, 0.65);
color: #FFF;
font-size: 14px;
line-height: 20px;
animation: npm-com-toast-mask-box-animation 0.3s forwards;
@keyframes npm-com-toast-mask-box-animation {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
}
}
.html {
display: inline-block;
text-align: center;
}
}
}
}
(4) 在npm-com-toast 文件夹下建立index.js
import Vue from 'vue';
import Popup from './npm-com-toast.vue'
const PopupBox = Vue.extend(Popup);
Popup.install = function (data) {
let instance = new PopupBox({
data
}).$mount()
document.body.appendChild(instance.$el)
Vue.nextTick(() => {
instance.show({
msg: instance.msg,
duration: instance.duration
})
})
}
export default Popup
(5) 在main.js里导入toast
import npmComToast from './components/npm-com-toast/index.js';
Vue.prototype.$toast = npmComToast.install;
(6) 在页面使用
this.$toast({
msg: '测试----',
duration: 2000,
})
最后,也有其他引入方式,具体看情况。