Vue js组件中引入Vue组件

用Vue一年多但是对Vue一些原理了解还是不够,研究这个问题花了一天,记录一下。

需求

需求:要实现地图上弹窗,弹窗内嵌入Vue组件,组件调用视频播放插件。
难点:要改造封装好的弹窗js组件,引入Vue组件,之前调用组件都是直接在.vue文件里import进来,写进components里就OK,可是放到js文件里还是第一次遇到。搜索了半天终于受到启发,可以用 Vue.component ,可是找到以后还是研究了半天写法才成功引入。

关键代码

在前面引入Vue组件

import videoPreview from "@/view/videoPreview"

创建组件实例

    constructor(map, {}) {
        this.component = Vue.component('video-preview', videoPreview)
        this.createComponent(this.instance)
    }
    createComponent(){ //创建组件实例但暂不挂载
        const component = Vue.component('video-preview')
        const instance = this.instance = new component()
        instance._props.videoData = {} //这里相当于平时 <videoPreview :videoData="videoData"></videoPreview> 写法里传值videoData
    }

创建html

        this.parent = document.createElement('div')
        this.parent.innerHTML = `
          <div class="pop-container">

          </div>`
        this.container = this.parent.querySelector('.pop-container')
        this.container.innerHTML = `
          <div class="videoWindow">
            <div id="video-preview"></div>
          </div>`

需要用到弹窗和组件的时候再挂载(如果需要反复调用,仅需挂载一次,否则会重复创建(需要显示视频播放插件时问题尤其明显))

this.instance.$mount("#video-preview")

调用组件内方法(假设组件内有方法 showPlugin()

this.instance.showPlugin()

参考

posted @ 2020-10-05 23:22  宇宙野牛  阅读(3113)  评论(0编辑  收藏  举报