前言
日常中我们要使用一个弹框组件的方式通常是先通过Vue.component 全局或是 component 局部注册后,然后在模版中使用。接下来我们尝试编程式的使用组件。
实现
其实步骤很简单

document.createElement
其实想要插入一个元素,通过 document.createElement 就可以实现,并非一定需要上面两步,但是涉及到组件的复杂度、样式设置、可维护性所以使用创建构造器的方式比较可行。
Vue.extend()
首先来定义这个弹框的结构和样式,就是正常的写组件即可
<template>
<div class="grid">
<h1 class="head">这里是标题</h1>
<div @click="close">{{ cancelText }}</div>
<div @click="onSureClick">{{ sureText }}</div>
</div>
</template>
<script>
export default {
props:{
close:{
type:Function,
default:()=>{}
},
cancelText:{
type:String,
default:'取消'
},
sureText:{
type:String,
default:'确定'
}
},
methods:{
onSureClick(){
// 其他逻辑
this.close()
}
}
};
</script>
将创建构造器和挂载到目标元素上的逻辑抽离出来,多处可以复用
export function extendComponents(component,callback){
const Action = Vue.extend(component)
const div = document.createElement('div')
document.body.appendChild(div)
const ele = new Action({
propsData:{
cancelText:'cancel',
sureText:'sure',
close:()=>{
ele.$el.remove()
callback&&callback()
}
}
}).$mount(div)
}
上面代码需要注意以下几点:
Vue.extend 和 Vue.component component 的区别
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!