目的: 封装一个类似于element中的Toast消息弹框组件
大致步骤:
-
首页创建一个Toast.vue文件, 在methods中定义一个show()方法和hide()方法
-
然后通过obj.install(Vue)方法组件注册挂载
// 1.创建组件构造器
const ToastConstructor = Vue.extend(Toast)
// 2.new 的方式, 根据构造器, 可以创建出一个组件对象
const toast = new ToastConstructor()
// 3. 将创建组件对象, 手动挂载到某一个元素上
toast.$mount(document.createElement('div'))
// 4. 将toast.$el对应的就是div
document.body.appendChild(toast.$el)
Vue.prototype.$toast = toast
Toast.vue文件
<template>
<div class="toast-container" v-if="isShow">
<span>{{ message }}</span>
</div>
</template>
<script>
export default {
name: '',
components: {},
data () {
return {
isShow: false,
message: ''
}
},
computed: {},
watch: {},
mounted () {},
methods: {
show (message = '请输入文本', durtion = 3000) {
this.isShow = true
this.message = message
setTimeout(() => {
this.isShow = false
this.message = ''
}, durtion)
}
}
}
</script>
<style lang='scss' scoped>
.toast-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
padding: 10px;
border-radius: 6px;
color: #fff;
}
</style>
然后我们就可以就可以通过 this.$message.show('你好呀. dialog', 3000)