vue自定义Toast插件
1. 创建一个Toast文件夹,新建Toast.vue和index.js这两个文件
2. Toast.vue
<template>
<!-- 定义过度动画 -->
<transition name="fade">
<div v-if="isShow" class="toast">
<span>{{ message }}</span>
</div>
</transition>
</template>
<script>
export default {
data() {
return {
message: "",
isShow: false,
};
},
};
</script>
<style scoped>
.toast {
display: flex;
position: fixed;
left: 50%;
top: 50%;
transform: translate3d(-50%, -50%, 0);
background: rgba(0, 0, 0, 0.7);
border-radius: 8px;
max-width: 70%;
padding: 16px;
min-height: 88px;
min-width: 88px;
font-size: 14px;
text-align: center;
white-space: pre-wrap;
align-items: center;
justify-content: center;
}
.toast span {
color: #fff;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity .5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
3. index.js
import ToastComponent from './Toast.vue'
const Toast = {}
let isShow = false
let toastVueObj
Toast.install = function (Vue) {
const ToastConstructor = Vue.extend(ToastComponent)
Vue.prototype.$toast = function (message) {
if (isShow) {
return;
}
isShow = true
toastVueObj = new ToastConstructor({
data: {
message,
isShow
}
})
let toastNode = toastVueObj.$mount().$el
document.body.appendChild(toastNode)
setTimeout(() => {
toastVueObj.isShow = isShow = false
}, 1500);
}
}
export default Toast
4. 用法
在入口文件main.js中引用
import Toast from './components/Toast/index'
Vue.use(Toast)
在需要的地方使用
this.$toast('Toast 显示的消息')

浙公网安备 33010602011771号