zoukankan      html  css  js  c++  java
  • vue2入坑随记(二) -- 自定义动态组件

     学习了Vue全家桶和一些UI基本够用了,但是用元素的方式使用组件还是不够灵活,比如我们需要通过js代码直接调用组件,而不是每次在页面上通过属性去控制组件的表现。下面讲一下如何定义动态组件。

     Vue.extend

     思路就是拿到组件的构造函数,这样我们就可以new了。而Vue.extend可以做到:https://cn.vuejs.org/v2/api/#Vue-extend

    // 创建构造器
    var Profile = Vue.extend({
      template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
      data: function () {
        return {
          firstName: 'Walter',
          lastName: 'White',
          alias: 'Heisenberg'
        }
      }
    })
    // 创建 Profile 实例,并挂载到一个元素上。
    new Profile().$mount('#mount-point')

    官方提供了这个示例,我们进行一下改造,做一个简单的消息提示框。

    动态组件实现

    创建一个vue文件。widgets/alert/src/main.vue

    <template>
     <transition name="el-message-fade">
    <div  v-show="visible" class="my-msg">{{message}}</div>
      </transition>
    </template>
    
    <script  >
        export default{
            data(){
               return{
                   message:'',
                   visible:true
               } 
            },
            methods:{
                close(){
                    setTimeout(()=>{
                         this.visible = false;
                    },2000)
                },
            },
            mounted() {
            this.close();
          }
        }
    </script>

    这是我们组件的构成。如果是第一节中,我们可以把他放到components对象中就可以用了,但是这儿我们要通过构造函数去创建它。再创建一个widgets/alert/src/main.js

    import Vue from 'vue';
    let MyMsgConstructor = Vue.extend(require('./main.vue'));
    
    let instance;
    
    var MyMsg=function(msg){
     instance= new MyMsgConstructor({
         data:{
             message:msg
    }})
    
    //如果 Vue 实例在实例化时没有收到 el 选项,则它处于“未挂载”状态,没有关联的 DOM 元素。可以使用 vm.$mount() 手动地挂载一个未挂载的实例。
    instance.$mount();
     
     document.body.appendChild(instance.$el)
     return instance;
    }
    
    
    export default MyMsg;

    require('./main.vue')返回的是一个组件初始对象,对应Vue.extend( options )中的options,这个地方等价于下面的代码:

    import alert from './main.vue'
    let MyMsgConstructor = Vue.extend(alert);

    而MyMsgConstructor如下。

     参考源码中的this._init,会对参数进行合并,再按照生命周期运行:

      Vue.prototype._init = function (options) {
        ...// merge options
        if (options && options._isComponent) {
          // optimize internal component instantiation
          // since dynamic options merging is pretty slow, and none of the
          // internal component options needs special treatment.
          initInternalComponent(vm, options);
        } else {
          vm.$options = mergeOptions(
            resolveConstructorOptions(vm.constructor),
            options || {},
            vm
          );
        }
    // expose real self
        vm._self = vm;
        initLifecycle(vm);
        initEvents(vm);
        initRender(vm);
        callHook(vm, 'beforeCreate');
        initInjections(vm); // resolve injections before data/props
        initState(vm);
        initProvide(vm); // resolve provide after data/props
        callHook(vm, 'created');
    
        ...
    
        if (vm.$options.el) {
          vm.$mount(vm.$options.el);
        }
      };

    而调用$mount()是为了获得一个挂载实例。这个示例就是instance.$el。

    可以在构造方法中传入el对象(注意上面源码中的mark部分,也是进行了挂载vm.$mount(vm.$options.el),但是如果你没有传入el,new之后不会有$el对象的,就需要手动调用$mount()。这个方法可以直接传入元素id。

     instance= new MessageConstructor({
         el:".leftlist",
         data:{
             message:msg
    }})

     这个el不能直接写在vue文件中,会报错。接下来我们可以简单粗暴的将其设置为Vue对象。

    调用

    在main.js引入我们的组件:

    //..
    import VueResource from 'vue-resource'
    import MyMsg from './widgets/alert/src/main.js';
    //..
    //Vue.component("MyMsg", MyMsg);
    Vue.prototype.$mymsg = MyMsg;

    然后在页面上测试一下:

    <el-button type="primary" @click='test'>主要按钮</el-button>
    //..

     methods:{
      test(){
      this.$mymsg("hello vue");
      }
     }

     

    这样就实现了基本的传参。最好是在close方法中移除元素:

     close(){
        setTimeout(()=>{
           this.visible = false;
           this.$el.parentNode.removeChild(this.$el);
          },2000)
       },

     回调处理

    回调和传参大同小异,可以直接在构造函数中传入。先修改下main.vue中的close方法:

    export default{
            data(){
               return{
                   message:'',
                   visible:true
               } 
            },
            methods:{
                close(){
                    setTimeout(()=>{
                         this.visible = false;
                          this.$el.parentNode.removeChild(this.$el);
    
                    if (typeof this.onClose === 'function') {
                     this.onClose(this);
                    }
                    },2000)
                },
            },
            mounted() {
            this.close();
          }
        }

    如果存在onClose方法就执行这个回调。而在初始状态并没有这个方法。然后在main.js中可以传入

    var MyMsg=function(msg,callback){
    
     instance= new MyMsgConstructor({
         data:{
             message:msg
        },
        methods:{
            onClose:callback
        } 
    })

    这里的参数和原始参数是合并的关系,而不是覆盖。这个时候再调用的地方修改下,就可以执行回调了。

       test(){
          this.$mymsg("hello vue",()=>{
            console.log("closed..")
          });
        },

    你可以直接重写close方法,但这样不推荐,因为可能搞乱之前的逻辑且可能存在重复的编码。现在就灵活多了。

    统一管理

     如果随着自定义动态组件的增加,在main.js中逐个添加就显得很繁琐。所以这里我们可以让widgets提供一个统一的出口,日后也方便复用。在widgets下新建一个index.js 

    import MyMsg from './alert/src/main.js';
    
    const components = [MyMsg];
    
    let install =function(Vue){
      components.map(component => {
        Vue.component(component.name, component);
      });
    
     Vue.prototype.$mymsg = MyMsg;
    
    }
    
    if (typeof window !== 'undefined' && window.Vue) {
      install(window.Vue);
    };
    
    export default {
        install
    }

    在这里将所有自定义的组件通过Vue.component注册。最后export一个install方法就可以了。因为接下来要使用Vue.use

    安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法将被作为 Vue 的参数调用。

    也就是把所有的组件当插件提供:在main.js中加入下面的代码即可。

    ...
    import VueResource from 'vue-resource'
    import Widgets from './Widgets/index.js'
    
    ...
    Vue.use(Widgets)

    这样就很简洁了。

    小结: 通过Vue.extend和Vue.use的使用,我们自定义的组件更具有灵活性,而且结构很简明,基于此我们可以构建自己的UI库。以上来自于对Element源码的学习。

    widgets部分源码:http://files.cnblogs.com/files/stoneniqiu/widgets.zip

    vue2入坑随记(一)-- 初始全家桶

  • 相关阅读:
    def __unicode__(self): 或 def __str__(self):
    通过ORM创建数据库链接
    单表查询的API介绍
    数据库的查看以及建立数据库
    基础数据类型
    表单及数据库
    flag标志位
    Console面板小技巧:
    angular入门试水-基本指令理解
    构造方法
  • 原文地址:https://www.cnblogs.com/stoneniqiu/p/6877460.html
Copyright © 2011-2022 走看看