前言
日常中我们要使用一个弹框组件的方式通常是先通过Vue.component 全局或是 component 局部注册后,然后在模版中使用。接下来我们尝试编程式的使用组件。
实现
其实步骤很简单
document.createElement
其实想要插入一个元素,通过 document.createElement 就可以实现,并非一定需要上面两步,但是涉及到组件的复杂度、样式设置、可维护性所以使用创建构造器的方式比较可行。
Vue.extend()
首先来定义这个弹框的结构和样式,就是正常的写组件即可
<template>
<div class="grid">
<h2 class="head">这里是标题</h2>
<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 的区别
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。