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入坑隨記(一)-- 初始全家桶


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM