1 编写组件
toast.vue
<template>
<transition name="fade">
<div v-show="visible">{{message}}</div>
</transition>
</template>
<script>
export default {
data () {
return {
visible: false,
message: ''
}
}
}
</script>
<style scoped>
div {
padding: 5px 20px;
color: #fff;
background-color: #3596ff;
text-align: center;
position: fixed;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
}
/* vue动画过渡效果设置 */
.fade-enter-active,
.fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}
</style>
index.js
import ToastComponent from './toast.vue'
const Toast = {
install: function (Vue) {
// 创建一个Vue的“子类”组件
const ToastConstructor = Vue.extend(ToastComponent)
// 创建一个该子类的实例,并挂载到一个元素上
const instance = new ToastConstructor()
// 将这个实例挂载到动态创建的元素上,并将元素添加到全局结构中
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
// 在Vue的原型链上注册方法,控制组件
Vue.prototype.$toast = (msg, duration = 1500) => {
instance.message = msg
instance.visible = true
setTimeout(() => {
instance.visible = false
}, duration)
}
}
}
export default Toast
2 在main.js中注册组件
import Toast from './components/toast'
Vue.use(Toast)
3 在任意组件中使用toast
this.$toast('***')
网友评论