<template>
<transition name="fade">
<div id="toast"
v-show="visible"
class="dialog-tips dialog-center">
{{message}}
</div>
</transition>
</template>
<script>
export default {
data () {
return {
visible: false,
message: ''
}
}
}
</script>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.dialog-tips {
position: fixed;
z-index: 100;
min-width: 100px;
padding: 15px 40px;
border-radius: 15px;
white-space: nowrap;
background-color: rgba(0,0,0,0.8);
box-shadow: 0 8px 30px 0 rgba(0, 0, 0, 0.363);
text-align: center;
color: #fff;
font-size: 15px
}
.dialog-center {
top: 30vh;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
创建 toast.js
import Toast from '../components/Toast.vue'
const toast = {}
toast.install = Vue => {
// 扩展 vue 插件
const ToastCon = Vue.extend(Toast)
const ins = new ToastCon()
// 挂载 dom
ins.$mount(document.createElement('div'));
// 添加到 body 后面
document.body.appendChild(ins.$el);
// 给 vue 原型添加 toast 方法
var timer=null;
Vue.prototype.$toast = (msg, duration = 2000) => {
clearTimeout(timer);
// 我们调用的时候 赋值 message
// 将 visible 设置为 true
// 默认 3s 之后 设置 为 false 关闭 toast
ins.message = msg
ins.visible = true
timer=setTimeout(() => {
ins.visible = false
}, duration)
}
}
export default toast
main.js引入
import toast from './plugins/toast'
Vue.use(toast);
代码中调用 this.$toast('轻提示!~')
网友评论