vue2 自定義動態(tài)組件所遇到的問題
下面講一下如何定義動態(tài)組件。
Vue.extend
思路就是拿到組件的構(gòu)造函數(shù),這樣我們就可以new了。而Vue.extend可以做到:https://cn.vuejs.org/v2/api/#Vue-extend
// 創(chuàng)建構(gòu)造器 var Profile = Vue.extend({ template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White', alias: 'Heisenberg' } } }) // 創(chuàng)建 Profile 實例,并掛載到一個元素上。 new Profile().$mount('#mount-point')
官方提供了這個示例,我們進行一下改造,做一個簡單的消息提示框。
動態(tài)組件實現(xiàn)
創(chuàng)建一個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>
這是我們組件的構(gòu)成。如果是第一節(jié)中,我們可以把他放到components對象中就可以用了,但是這兒我們要通過構(gòu)造函數(shù)去創(chuàng)建它。再創(chuàng)建一個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 選項,則它處于“未掛載”狀態(tài),沒有關(guān)聯(lián)的 DOM 元素??梢允褂?vm.$mount() 手動地掛載一個未掛載的實例。 instance.$mount(); document.body.appendChild(instance.$el) return instance; } export default MyMsg; require('./main.vue')返回的是一個組件初始對象,對應(yīng)Vue.extend( options )中的options,這個地方等價于下面的代碼: import alert from './main.vue' let MyMsgConstructor = Vue.extend(alert);
而MyMsgConstructor如下。
參考源碼中的this._init,會對參數(shù)進行合并,再按照生命周期運行:
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); } };
而調(diào)用$mount()是為了獲得一個掛載實例。這個示例就是instance.$el。
可以在構(gòu)造方法中傳入el對象(注意上面源碼中的mark部分,也是進行了掛載vm.$mount(vm.$options.el),但是如果你沒有傳入el,new之后不會有$el對象的,就需要手動調(diào)用$mount()。這個方法可以直接傳入元素id。
instance= new MessageConstructor({ el:".leftlist", data:{ message:msg }})
這個el不能直接寫在vue文件中,會報錯。接下來我們可以簡單粗暴的將其設(shè)置為Vue對象。
調(diào)用
在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"); } }
這樣就實現(xiàn)了基本的傳參。最好是在close方法中移除元素:
close(){ setTimeout(()=>{ this.visible = false; this.$el.parentNode.removeChild(this.$el); },2000) },
回調(diào)處理
回調(diào)和傳參大同小異,可以直接在構(gòu)造函數(shù)中傳入。先修改下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方法就執(zhí)行這個回調(diào)。而在初始狀態(tài)并沒有這個方法。然后在main.js中可以傳入
var MyMsg=function(msg,callback){ instance= new MyMsgConstructor({ data:{ message:msg }, methods:{ onClose:callback } })
這里的參數(shù)和原始參數(shù)是合并的關(guān)系,而不是覆蓋。這個時候再調(diào)用的地方修改下,就可以執(zhí)行回調(diào)了。
test(){ this.$mymsg("hello vue",()=>{ console.log("closed..") }); },
你可以直接重寫close方法,但這樣不推薦,因為可能搞亂之前的邏輯且可能存在重復(fù)的編碼?,F(xiàn)在就靈活多了。
統(tǒng)一管理
如果隨著自定義動態(tài)組件的增加,在main.js中逐個添加就顯得很繁瑣。所以這里我們可以讓widgets提供一個統(tǒng)一的出口,日后也方便復(fù)用。在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 方法。如果插件是一個函數(shù),它會被作為 install 方法。install 方法將被作為 Vue 的參數(shù)調(diào)用。
也就是把所有的組件當(dāng)插件提供:在main.js中加入下面的代碼即可。
... import VueResource from 'vue-resource' import Widgets from './Widgets/index.js' ... Vue.use(Widgets)
這樣就很簡潔了。
小結(jié): 通過Vue.extend和Vue.use的使用,我們自定義的組件更具有靈活性,而且結(jié)構(gòu)很簡明,基于此我們可以構(gòu)建自己的UI庫。以上來自于對Element源碼的學(xué)習(xí)。
widgets部分源碼:http://files.cnblogs.com/files/stoneniqiu/widgets.zip
以上所述是小編給大家介紹的vue2 自定義動態(tài)組件所遇到的問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
vue2.0 中使用transition實現(xiàn)動畫效果使用心得
這篇文章主要介紹了vue2.0 中使用transition實現(xiàn)動畫效果使用心得,本文通過案例知識給大家介紹的非常詳細,需要的朋友參考下吧2018-08-08webpack 3 + Vue2 使用dotenv配置多環(huán)境的步驟
這篇文章主要介紹了webpack 3 + Vue2 使用dotenv配置多環(huán)境,env文件在配置文件都可以用, vue頁面用的時候需要在 webpack.base.conf.js 重新配置,需要的朋友可以參考下2023-11-11