ui实现一个简易的$message方法(2)

但是我们该怎么调用呢,参考element-ui中的使用方式this.$message,是把组件的入口方法挂载到Vue的原型链上,并且在此之前应该实例化了该组件,接下来我们就要实例化组件,然后将组件实例挂载到body上,并且将实例上的入口方法加在Vue原型链上。

这里使用到了我们公司一位大佬参考react写的vue中的传送门方法portal,主要思路是将组件挂载新的Vue上,并实例化,然后再将新实例挂载到body下面(这样也防止DOM层级嵌套产生的zIndex无法覆盖等问题),最后将指定方法添加到Vue原型链上。

import Vue, {VueConstructor} from "vue"; interface Param { cmp: VueConstructor & {instance?: () => any}; name: string; method?: string; target?: string | HTMLElement; props?: any; } export default function portal(param: Param){ let {cmp, name, method, target = document.body, props = {}} = param if(typeof target === 'string') target = document.querySelector(target) as HTMLElement; method = method || 'show' cmp.instance = ()=>{ let instance = new Vue({ render(h){ return h(cmp, {props}) } }) instance.$mount(); // 将instance.$el放到想放的位置 (target as HTMLElement).appendChild(instance.$el); return instance.$children[0]; } const instance = cmp.instance() Vue.prototype[`$${name}`] = instance[method]; }

接着,在Vue项目入口文件中使用传送门方法将Msg组件挂载上去就可以在组件中使用了。

portal({ name: 'msg', cmp: MsgBox, method: 'addMsg' })

到此这篇关于仿照Element-ui实现一个简易的$message方法的文章就介绍到这了,更多相关Element-ui $message内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

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

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