弹窗组件的基础用法
// 引入notice组件
import Notice from '@/components/Notice';
// 引入create方法
import create from '@/utils/create';
create(Notice, {
title: '弹窗',
message: '成功',
duration: 3000
}).show()
从使用方式上可以得知需要实现一个create方法,该方法接受一个组件,即弹窗组件自身
一、创建弹窗组件
<template>
<div v-if="isShow">
<!-- 渲染提示类容 -->
<h3>{{title}}</h3>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
name: 'VueStudyIndex',
// 接受props
props: {
title: {
type: String,
default: ''
},
message: {
type: String,
default: ''
},
duration: {
type: Number,
default: 0
}
},
data() {
return {
isShow: false
};
},
mounted() {
},
methods: {
show() {
this.isShow = true
setTimeout(() => {
this.hide()
}, this.duration)
},
hide() {
this.isShow = false
this.remove()
}
},
};
</script>
<style lang="scss" scoped>
</style>
弹窗组件自身通过v-if去控制显示与隐藏
二、实现create方法
import Vue from 'vue'
export default function (componentName, props) {
//0、先创建vue实例
const vm = new Vue({
render(h) {
//渲染传入进来的组件,此时的props会传给上面创建的弹窗组件
return h(componentName, { props })
}
}).$mount()
// 1、vm会创建组件实例
// 通过$children获取该组件实例
const comp = vm.$children[0]
// 追加到body
document.body.appendChild(vm.$el)
//清理函数
comp.remove = () => {
document.body.removeChild(vm.$el)
vm.$destroy()
}
//返回组件实例
return comp
}