天天看点

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中声明,直接在模板中使用即可。

继续阅读