Vue2将组件插入到特定元素

576 阅读1分钟
  • 方法:
/**
 * @param {要插入到dom元素} dom
 * @param {插入的组件} component
 * @param {插入组件的props参数} propsData
 */
import Vue from 'vue';

export default function(dom, component, propsData) {
  if (!dom || !component) return;
  const mountNode = document.createElement('div');
  mountNode.id = 'append-to-dom';

  var MyPartial = Vue.extend(component);
  const partial = new MyPartial({
    propsData
  });

  dom.append(mountNode);
  partial.$mount('#append-to-dom');
}
  • 使用:
将ImageViewer组件插入到body中

import ImageViewer from '@/components/ImageViewer';

const body = document.querySelector('body');
const propsData = {
    urlList: this.srcList,
    onClose: () => {
      const imageView = document.querySelector('.el-image-viewer__wrapper');
      if (!imageView) return;
      body.removeChild(imageView);
    },
};

appendToDom(body, ImageViewer, propsData);