vue, how dynamically, programically, on click add component to the DOM specific place?

落爺英雄遲暮 提交于 2020-02-24 10:31:07

问题


I need to add a dynamically imported component, just add a virtual tag to specific place in DOM structure. Unfortunately, every method that I found, didn't solve my problem.

How I try it first:

parent component (Editor.vue):

<template>
  <div>
    <div class="toolbar">
        <button @click="addContainer">ADD CONTAINER</button>
    </div>
    <div id="editor" ref="editor" contenteditable="true">
       //here, when in conteneditable div is coursor I need to add dynamically, programically virtual tag <container />
    </div>        
  </div>
</template>

and javascript

<script>
import container from '../container/Container.vue';

export default {
  name: "editor",
  components: {
    container
  },
  data() {
    return {};
  },
  methods: {
    addContainer(){          
      document.execCommand('insertHTML', false, <container />); // execCommand let me add html in specyfic place, but I have error Unexpected token

    }
  },
};

And child component that has to be adding how many times user need in exactly place then user need (Container.vue)

<template>
  <div
    class="container editor--space"
    @mouseover="highlightIn"
    @mouseout="highlightOut"
    contenteditable="true"
  >
    <div
      class="editor--labelspace"
      v-if="showLabel"
      contenteditable="false"
    >
      container
    </div>
    {{ container }}
  </div>
</template>

and javascript

<script>
export default {
  name: "container",
  data() {
    return {
      showLabel: false,
      container: "Container here ..."
    };
  },
  methods: {
    highlightIn(){
      this.showLabel = true;
    },
    highlightOut(){
      this.showLabel = false;
    }
  }
};
</script>

Maybe someone can give me some idea, how to do this?


回答1:


By the help of this: https://stackoverflow.com/a/2925633/7741865 and by dynamically creating the child components, you should achieve what you want. Sample:

addContainer() {
  // dynamically create component, replace 'Child' with your component
  var ComponentClass = Vue.extend(Child);
  var instance = new ComponentClass();
  instance.$mount();

  // get the caret position and insert component at that place
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      range.insertNode(instance.$el);
      // remove the highlight (if you want)
      window.getSelection().removeAllRanges();
    }
  }
}

SANDBOX



来源:https://stackoverflow.com/questions/59321780/vue-how-dynamically-programically-on-click-add-component-to-the-dom-specific

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!