天天看點

vue中使用時動态挂載元件

元件動态挂載,調用showTasks方法時才去初始化taskDialog元件。

async showTasks() {
      // 注冊元件
      const compName = 'taskDialog'
      if (this.$options.components[compName]) { // 判斷元件是否已經引入了
        this.$refs.taskDialog && this.$refs.taskDialog.changeShow()  //是,直接顯示
      } else { // 否,挂載到vue上,這裡使用了動态導入import
        this.$options.components[compName] = await import(`./components/${compName}.vue`)
      }
      this.taskDialogInit = true
    }
           

在taskDialog元件中,mounted方法中通知父元件

this.$emit("mounted")
           

父元件中監聽子元件mounted事件

<task-dialog v-if="taskDialogInit" ref="taskDialog" @mounted="taskDialogMounted"/>
           

父元件監聽到子元件加載完畢(可以在子元件中完成了資料請求後觸發),顯示子元件

taskDialogMounted() {
   this.$refs.taskDialog && this.$refs.taskDialog.changeShow()
},
           

動态挂載的元件不需要在頂部import了,也無需在components中聲明,直接在模闆中使用即可。

繼續閱讀