美文网首页
自定义全局组件

自定义全局组件

作者: 陈成熟 | 来源:发表于2019-12-05 22:00 被阅读0次

    经常的,业务中需要用到一些全局的组件,类似Toast、弹窗等,如果我们在每个页面都单独的去引入的话,就会比较麻烦,那么,如何将组件作为全局组件调用呢?这样的好处是在每个页面调用的时候,不需要引入,直接调用,并将它挂载在body元素中,不会对我们的页面样式造成影响。

    下面我们来看看如何自定义一个全局组件。
    以一个Toast举例
    在components文件夹里,创建一个Notice.vue。

    <template>
      <div class="alert">
        <div class="alert-container" v-for="item in alerts" :key="item.id">
          <div class="alert-content">{{item.content}}</div>
        </div>
      </div>
    </template>
    

    因为需要用到alerts,所以创建一个alerts数组。
    在create()里,需要做一个id的自增控制。

    name:'notice',
     data() {
           return {
                    alerts: []
          }
    },
    created () {
           // id自增控制
           this.id = 0;
     }
    

    代表来一条alert,就把id置为0,然后自增一下。
    然后在里面添加2个方法,add()和del()。
    add用来创建一个新的alert。

    add(options) {
       //id放在this里,所以不是响应式的
      const id = 'id_'+(this.id++);
      //把用户传进来的options展开,和id进行合并
      const _alert = { ...options, id: id };
      this.alerts.push(_alert);
      // 自动关闭
      const duration = options.duration || 1; //单位秒
      setTimeout(() => {
        this.del(id)
      },duration*1000);
    },
    del(id) {
         for(let i = 0;i < this.alerts.length; i++) {
              const element = this.alerts[i];
              if(element.id === id) {
                   this.alerts.splice(i,1);
                   break;
             }
         }
    }
    

    完善一下样式

    <style scoped lang="stylus">
    .alert {
      position: fixed;
      width: 100%;
      top: 30px;
      left: 0;
      text-align: center;
    
      .alert-content {
        display: inline-block;
        padding: 8px;
        background: #fff;
        margin-bottom: 10px;
      }
    }
    </style>
    

    写完组件之后,如何全局的调用它?

    1. 最快的方式就是,直接使用别人写好的api,比如cube-ui里的createAPI。
      在main.js里引入createAPI
    import { createAPI } from 'cube-ui';
    import Notice from './components/Notice.vue';
    //创建$createNotice
    createAPI(Vue,Notice,true); //参数3表示单例模式
    

    然后在需要调用Notice的地方,比如Home.vue里

    const notice = this.$createNotice();  //表示创建了一个notice实例,挂载在body上
    notice.add({content:'lalala',duration:2})  //调用add方法
    
    1. 我们自定义一个服务,全局调用Notice
      先创建一个services文件夹,创建一个notice.js
    import Notice from '@/components/Notice.vue';
    import Vue from 'vue';
    
    // 给Notice添加一个创建组件实例的方法,可以动态编译自身模板并挂载
    Notice.getInstance = props => {
        // 创建一个Vue实例
        const instance = new Vue({
            // 渲染函数: 用于渲染指定模板为虚拟DOM  
            // h是一个渲染函数,可以把我们传入的模板编译成虚拟DOM
            render(h){ 
                // <Notice foo="bar"></Notice>
                return h(Notice, {props})
            }
        }).$mount(); // 执行挂载
        
        // $mount() 是outerHTML,所以$mount('body')是不可以的,会替换body。
        // 所以不指定选择器,则模板将被渲染为文档之外的元素
    
        // 必须使用原生的dom api把它插入文档中 
        // $el是渲染的Notice中真正的dom元素
        document.body.appendChild(instance.$el);
    
        // 获取Notice实例   instance是vue实例,instance.$children取出实例下的虚拟DOM元素
        // $children指的是当前Vue实例中包含的所有组件实例 $children[0]就是根,即是Notice实例
        const notice = instance.$children[0];
        return notice;
    }
    

    接下来设计一个单例模式,在全局范围唯一的创建一个Notice实例,保证它的唯一性

    let msgInstance = null;
    function getInstance() {
        msgInstance = msgInstance || Notice.getInstance();
        return msgInstance;
    }
    

    暴露接口

    export default {
        // info方法,参数给一个默认值
        info({duration=2,content=''}){
            getInstance().add({
                content,duration
            });
        }
    }
    

    在创建完这个notice.js后,需要去main.js注册

    import notice from '@/services/notice';
    
    Vue.prototype.$notice = notice;
    

    最后去Home.vue里使用$notice。

    this.$notice.info({
            duration: 3,
            content: '一些消息内容'
    })
    

    这样就实现了自定义全局组件,并调用

    相关文章

      网友评论

          本文标题:自定义全局组件

          本文链接:https://www.haomeiwen.com/subject/jexjgctx.html