溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue自定義動(dòng)態(tài)組件的方法是什么

發(fā)布時(shí)間:2022-10-28 09:47:06 來(lái)源:億速云 閱讀:120 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容主要講解“vue自定義動(dòng)態(tài)組件的方法是什么”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“vue自定義動(dòng)態(tài)組件的方法是什么”吧!

 Vue.extend

 思路就是拿到組件的構(gòu)造函數(shù),這樣我們就可以new了。而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 實(shí)例,并掛載到一個(gè)元素上。
new Profile().$mount('#mount-point')

官方提供了這個(gè)示例,我們進(jìn)行一下改造,做一個(gè)簡(jiǎn)單的消息提示框。

動(dòng)態(tài)組件實(shí)現(xiàn)

創(chuàng)建一個(gè)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對(duì)象中就可以用了,但是這兒我們要通過(guò)構(gòu)造函數(shù)去創(chuàng)建它。再創(chuàng)建一個(gè)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 實(shí)例在實(shí)例化時(shí)沒(méi)有收到 el 選項(xiàng),則它處于“未掛載”狀態(tài),沒(méi)有關(guān)聯(lián)的 DOM 元素。可以使用 vm.$mount() 手動(dòng)地掛載一個(gè)未掛載的實(shí)例。
instance.$mount();
 document.body.appendChild(instance.$el)
 return instance;
}
export default MyMsg;
require('./main.vue')返回的是一個(gè)組件初始對(duì)象,對(duì)應(yīng)Vue.extend( options )中的options,這個(gè)地方等價(jià)于下面的代碼:
import alert from './main.vue'
let MyMsgConstructor = Vue.extend(alert);

而MyMsgConstructor如下。

 參考源碼中的this._init,會(huì)對(duì)參數(shù)進(jìn)行合并,再按照生命周期運(yùn)行:

 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()是為了獲得一個(gè)掛載實(shí)例。這個(gè)示例就是instance.$el。

vue自定義動(dòng)態(tài)組件的方法是什么

可以在構(gòu)造方法中傳入el對(duì)象(注意上面源碼中的mark部分,也是進(jìn)行了掛載vm.$mount(vm.$options.el),但是如果你沒(méi)有傳入el,new之后不會(huì)有$el對(duì)象的,就需要手動(dòng)調(diào)用$mount()。這個(gè)方法可以直接傳入元素id。

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

 這個(gè)el不能直接寫(xiě)在vue文件中,會(huì)報(bào)錯(cuò)。接下來(lái)我們可以簡(jiǎn)單粗暴的將其設(shè)置為Vue對(duì)象。

調(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;

然后在頁(yè)面上測(cè)試一下:

<el-button type="primary" @click='test'>主要按鈕</el-button>
//..
 methods:{
 test(){
 this.$mymsg("hello vue");
 }
 }

這樣就實(shí)現(xiàn)了基本的傳參。最好是在close方法中移除元素:

vue自定義動(dòng)態(tài)組件的方法是什么

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í)行這個(gè)回調(diào)。而在初始狀態(tài)并沒(méi)有這個(gè)方法。然后在main.js中可以傳入

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

這里的參數(shù)和原始參數(shù)是合并的關(guān)系,而不是覆蓋。這個(gè)時(shí)候再調(diào)用的地方修改下,就可以執(zhí)行回調(diào)了。

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

你可以直接重寫(xiě)close方法,但這樣不推薦,因?yàn)榭赡芨銇y之前的邏輯且可能存在重復(fù)的編碼。現(xiàn)在就靈活多了。

統(tǒng)一管理

 如果隨著自定義動(dòng)態(tài)組件的增加,在main.js中逐個(gè)添加就顯得很繁瑣。所以這里我們可以讓widgets提供一個(gè)統(tǒng)一的出口,日后也方便復(fù)用。在widgets下新建一個(gè)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
}

在這里將所有自定義的組件通過(guò)Vue.component注冊(cè)。最后export一個(gè)install方法就可以了。因?yàn)榻酉聛?lái)要使用Vue.use。

安裝 Vue.js 插件。如果插件是一個(gè)對(duì)象,必須提供 install 方法。如果插件是一個(gè)函數(shù),它會(huì)被作為 install 方法。install 方法將被作為 Vue 的參數(shù)調(diào)用。

也就是把所有的組件當(dāng)插件提供:在main.js中加入下面的代碼即可。

...
import VueResource from 'vue-resource'
import Widgets from './Widgets/index.js'

...
Vue.use(Widgets)

Vue的優(yōu)點(diǎn)

Vue具體輕量級(jí)框架、簡(jiǎn)單易學(xué)、雙向數(shù)據(jù)綁定、組件化、數(shù)據(jù)和結(jié)構(gòu)的分離、虛擬DOM、運(yùn)行速度快等優(yōu)勢(shì),Vue中頁(yè)面使用的是局部刷新,不用每次跳轉(zhuǎn)頁(yè)面都要請(qǐng)求所有數(shù)據(jù)和dom,可以大大提升訪問(wèn)速度和用戶體驗(yàn)。

到此,相信大家對(duì)“vue自定義動(dòng)態(tài)組件的方法是什么”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI