加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 移动互联 > 正文

仿照Element-ui实现一个简易的$message方法

发布时间:2020-11-04 09:48:55 所属栏目:移动互联 来源:网络整理
导读:这篇文章首要先容了模拟Element-ui实现一个浅显的$message要领,文中通过示例代码先容的很是具体,对各人的进修可能事变具有必然的参考进修代价,必要的伴侣们下

可是我们该怎么挪用呢,参考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组件挂载上去就可以在组件中行使了。

到此这篇关于模拟Element-ui实现一个浅显的$message要领的文章就先容到这了,更多相干Element-ui $message内容请搜刮剧本之家早年的文章或继承赏识下面的相干文章但愿各人往后多多支持剧本之家!

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读