vue2 自訂動態組件所遇到的問題,vue2自訂動態組件

來源:互聯網
上載者:User

vue2 自訂動態組件所遇到的問題,vue2自訂動態組件

下面講一下如何定義動態組件。

 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 自訂動態組件所遇到的問題,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.