vue2 中怎么自定義動態(tài)組件,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

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ù)的編碼。現(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)
看完上述內(nèi)容,你們掌握vue2 中怎么自定義動態(tài)組件的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站chinadenli.net,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)站標(biāo)題:vue2中怎么自定義動態(tài)組件-創(chuàng)新互聯(lián)
本文地址:http://chinadenli.net/article16/ddpsgg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計、網(wǎng)站導(dǎo)航、網(wǎng)站設(shè)計公司、商城網(wǎng)站、用戶體驗、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)