Vue.extend 编程式插入组件的实现

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

实现

其实步骤很简单

通过 Vue.extend() 创建构造器

通过 Vue.$mount() 挂载到目标元素上

目标实现一个 alert 弹框,确认和取消功能如下图

document.createElement

其实想要插入一个元素,通过 document.createElement 就可以实现,并非一定需要上面两步,但是涉及到组件的复杂度、样式设置、可维护性所以使用创建构造器的方式比较可行。

Vue.extend()

首先来定义这个弹框的结构和样式,就是正常的写组件即可

<template> <div> <h1>这里是标题</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 实例

实例化时可以向这个实例传入参数,但是需要注意的是 props 的值需要通过 propsData 属性来传递

得到 Vue 实例后,我们需要通过一个目标元素来挂载它,有人首先会想到挂载到 #app 上,这个挂载的过程是将目标元素的内容全部替换,所以一旦挂载到 #app 上,该元素的所有子元素都会消失被替换

针对第3点,所以创建了一个 div 元素插入到 body 中,我们将想要挂载的内容替换到这个div上

Vue.extend 和 Vue.component component 的区别

Vue.component component两者都是需要先进行组件注册后,然后在 template 中使用注册的标签名来实现组件的使用。Vue.extend 则是编程式的写法

关于组件的显示与否,需要在父组件中传入一个状态来控制 或者 在组件外部用 v-if/v-show 来实现控制,而 Vue.extend 的显示与否是手动的去做组件的挂载和销毁。

Vue.component component 在组件中需要使用 slot 等自定义UI时更加灵活,而 Vue.extend 由于没有 template的使用,没有slot 都是通过 props 来控制UI,更加局限一些。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/f4ef980b69be9d86b743ce4436c725ff.html