手撸一个VUE toast全局可安装组件
安装vue vue elementUi
不用elementui 可自定下载iconfont来替换图标
预览
懂VUE的都懂 再次不赘述
代码结构
src/main.vue
<template>
<div v-show="show" class="biztoast">
<div class="toast_container">
<i :class="iconClass"></i>
<div class="toast-text">{{message}}</div>
</div>
</div>
</template>
<script>
const TYPE_CLASSES_MAP = {
success: "el-icon-success",
warning: "el-icon-warning",
error: "el-icon-error",
loading: "el-icon-loading"
};
export default {
props: {
show: Boolean,
message: {
type: String,
default: "加载中"
},
type: {
type: String,
default: "loading"
}
},
computed: {
iconClass() {
return TYPE_CLASSES_MAP[this.type] || "el-icon-loading";
}
}
};
</script>
<style scoped lang="scss">
.biztoast {
width: 100%;
.toast_container {
background: rgba($color: #000000, $alpha: 0.8);
border-radius: 8px;
color: #fff;
position: fixed;
width: 100px;
height: 100px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 2020;
text-align: center;
[class^="el-icon-"] {
line-height: 65px;
font-size: 30px;
}
.toast-text {
font-size: 16px;
}
}
}
</style>
index.js
import Vue from 'vue'
import toastComponent from './src/main'
let instance;
const ToastConstructor = Vue.extend(toastComponent)
instance = new ToastConstructor({
el: document.createElement("div")
})
instance.show = false;
const bizToast = {
show(options = {}) {
instance.show = true;
if (options) {
instance.message = typeof options === 'string' ? options : options.message;
instance.type = options.type;
document.body.appendChild(instance.$el);
if(options.type != 'loading'){ //结果态 2S后销毁
setTimeout(() => {
this.hide()
}, 2000);
}
}
},
hide() {
instance.show = false;
if (instance.$el) {
document.body.removeChild(instance.$el)
}
}
}
export default {
install() {
if (!Vue.$biztoast) {
Vue.$biztoast = bizToast
}
Vue.mixin({
created() {
this.$biztoast = Vue.$biztoast
}
})
}
}
组件安装
import Vue from 'vue'
import bizToast from '@/components/bizToast';
Vue.use(bizToast)
组件调用
//loading 非loading态会在2S内自动关闭清除组件
this.$biztoast.show({ message: "加载中", type: "loading" });
//success
this.$biztoast.show({ message: "加载完成", type: "success" });
//...
//关闭
this.$biztoast.hide();