美文网首页
vue 常用组件工程化,简化组件的调用

vue 常用组件工程化,简化组件的调用

作者: sponing | 来源:发表于2018-05-24 17:58 被阅读0次

    一、运用window全局、$emit、$on组件化

    main.js

    window.$channel = $channel;
    Vue.prototype.NavBarConfig = (config) => {
      $channel.$emit('NavTransitionEvent', config)
    }
    

    在其他页面直接可以thisNavBarConfig({}), 比如:

    this.NavBarConfig({
          title: "差旅费事前申请单",
          back: this.goNativeApp,
          hide: false,
          menu: {
            // icon: 'iconfont icon-fenxiang',
            text: {
              value: "下一步",
              class: "",
              style: {}
            },
            handle: () => {
              this.nextClick();
            }
          }
        });
    

    解析

    1、this.NavBarConfigthis指向VueVue.prototype.NavBarConfig;
    调用 $channel.$emit('NavTransitionEvent', config)
    2、$channel定义为window.$channel,因此所有页面都能调用$channel

    header.vue

    // 其他元素省略
    created: function() {
        $channel.$on('NavTransitionEvent', (config) => {
          this.reset();
          if (!config) {
            return;
          }
          this.config.isText = config.menu && config.menu.text ? true : false;
          Object.assign(this.config, config);
          if (this.config.hide) {
            this.$emit('on-hide', true) // header关闭,传值父组件将其关闭
          } else {
            this.$emit('on-hide', false)
          }
        })
      },
    

    解析
    1、第一次created header组件未显示,等this.NavBarConfig()调用时,才再次启动调用

    二、用Vue.extend构建消息提示组件

    // 假设toast.vue已写好
    // index.js
    import Vue from 'vue';
    import OriginToast from '../toast/toast.vue';
    
    const Toast = Vue.extend(OriginToast);
    
    let instance,
        active = false;
    export default {
        show(message = ' ') {
            if(active) return;
            /* global document:true */
            if(!instance) {
                instance = new Toast({
                    el: document.createElement('div'),
                });
                document.body.appendChild(instance.$el);
            }
            active = true;
            instance.message = message;
            instance.type = 'loading';
            instance.position = 'center';
            Vue.nextTick(() => {
                instance.show();
            });
        },
        hide() {
            instance.hide();
            active = false;
        },
        toggle(message) {
            return active ? this.hide() : this.show(message);
        },
    };
    window.$loading = loading;
    
    // 其他页面调用
    loading.toggle(‘正在加载...’);
    

    材料: 用Vue.extend构建消息提示组件

    相关文章

      网友评论

          本文标题:vue 常用组件工程化,简化组件的调用

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