效果图:
根据参数分别有4种样式:success,info,warning,error,none
开发者可以根据自身需要替换对应的图标即可。
下面是代码:
index.js
import Vue from 'vue';
import toast from './toast.vue';
export default {
install(Vue) {
const defaults = {
show:false,
text:'系统异常,请稍后重试。',
duration:'3000',
type:'none'
};
const toastVueConstructor = Vue.extend(toast);
toastVueConstructor.prototype.close = function() {
var vm=this;
this.$on('after-leave', _ => {
if (vm.$el && vm.$el.parentNode) {
vm.$el.parentNode.removeChild(vm.$el);
}
this.$destroy();
});
vm.show = false;
};
Vue.prototype.$toast = (options = {}) => {
if (Vue.prototype.$isServer) return;
options = Object.assign({}, defaults, options);
let parent = document.body ;
let instance = new toastVueConstructor({
el: document.createElement('div'),
data: options
});
parent.appendChild(instance.$el);
Vue.nextTick(() => {
instance.show = true;
setTimeout(function(){
instance.close();
},options.duration)
});
return instance;
};
},
};
toast.vue
<template>
<transition name="mei-toast-fade">
<div v-if="show" class="toast-container">
<div v-if="type!=='none'" class="toast-icon">
<i :class="['iconfont',iconClass]"></i>
</div>
<div class="toast-text">{{text?text:'系统异常,请稍后重试'}}</div>
</div>
</transition>
</template>
<script type="text/babel">
const typeMap = {
success: 'icon-success',
info: 'icon-prompt',
warning: 'icon-prompt',
error: 'icon-error',
none: ''
};
export default {
data() {
return {
show:false,
text:'',
type:''
};
},
computed: {
iconClass() {
return typeMap[this.type];
}
},
};
</script>
<style lang="less" >
.toast-container{
max-width:60%;
min-width: 120px;
padding: 10px 14px;
color: rgb(255, 255, 255);
text-align: center;
border-radius: 4px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
z-index: var(--toast-index);
background: rgba(0, 0, 0,.7);
display: flex;
flex-direction: column;
align-items: center;
.toast-icon{
width: 80px;
height: 80px;
text-align: center;
line-height: 80px;
font-size: 60px;
}
.toast-text{
color: #ffffff;
font-size: 14px;
}
}
.mei-toast-fade-enter-active {
transition: all 0.3s linear;
}
.mei-toast-fade-leave-active {
transition: all 0.3s linear;
}
.mei-toast-fade-enter, .mei-toast-fade-leave-to{
opacity: 0;
}
</style>
通过添加实例方法,把插件添加到vue.prototype上来实现。
在使用之前需要将插件挂载到Vue全局实例上:
main.js
import VueToast from './components/toast/index.js';
Vue.use(VueToast);
完成上述条件后,就可以在你的vue项目中使用啦:
this.$toast({
show: true,
type: 'success',
duration: 3000,
text: "成功"
});