封装vue的弹窗组件
先写一个工具函数,创建组件实例// 创建指定组件实例并挂载于body上import Vue from 'vue';export default function create(Component, props) {// 0. 先创建vue实例const vm = new Vue({render(h) {// render方法提供给我们一个h函数,它可以渲染VNodereturn h(Compone
·
先写一个工具函数,创建组件实例
// 创建指定组件实例并挂载于body上
import Vue from 'vue';
export default function create(Component, props) {
// 0. 先创建vue实例
const vm = new Vue({
render(h) {
// render方法提供给我们一个h函数,它可以渲染VNode
return h(Component, {props})
}
}).$mount(); // 更新操作
// 1. 上面vm帮我们创建组件实例
// 2. 通过$children获取该组件实例
console.log(vm.$root);
const comp = vm.$children[0];
// 3. 追加至body
document.body.appendChild(vm.$el);
// 4. 清理函数
comp.remove = () => {
document.body.removeChild(vm.$el);
vm.$destroy();
}
// 5. 返回组件实例
return comp;
}
Notice组件
<template>
<div v-if="isShow">
<h3>{{title}}</h3>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: ""
},
message: {
type: String,
default: ""
},
duration: {
type: Number,
default: ""
}
},
data() {
return {
isShow: false
};
},
methods: {
show() {
this.isShow = true;
setTimeout(() => {
this.hide()
}, this.duration);
},
hide() {
this.isShow = false;
this.remove();
}
}
};
</script>
<style lang="scss" scoped>
</style>
使用组件的地方
methods: {
onLogin() {
// 创建弹窗实例
let notice;
this.$refs.loginForm.validate(isValid => {
notice = create(Notice, {
title: "xxx",
message: isValid ? "登录!!!" : "有错!!!",
duration: 10000
});
notice.show();
});
}
}
更多推荐


所有评论(0)