html - vue,如何以编程方式动态地单击将组件添加到 DOM 特定位置?

标签 html vue.js dynamic tags

我需要添加一个动态导入的组件,只需在 DOM 结构中的特定位置添加一个虚拟标签。不幸的是,我找到的每种方法都没有解决我的问题。

我如何首先尝试:

父组件(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>

和 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

    }
  },
};

和必须添加多少次用户需要的子组件然后用户需要(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>

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

也许有人可以给我一些想法,如何做到这一点?

最佳答案

借助于此:https://stackoverflow.com/a/2925633/7741865通过动态创建子组件,您应该可以实现您想要的。样本:

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

关于html - vue,如何以编程方式动态地单击将组件添加到 DOM 特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321780/

相关文章:

javascript - Vue.js 2.0 : Apply vue component rendered using v-html, 编译标记

html - 如何将用户定义的 CSS 类添加到我的自定义小部件呈现代码中?

bash - libipopt.so.1 : Cannot open shared object file

javascript - <html> 比屏幕宽

javascript - 事件源 -> 服务器批量返回事件流而不是 block 返回

vue.js - Vuejs Axios 数据未显示

javascript - Vue JS 设置要选择的填充选择中的第一项

vue.js - Vue 路由器链接警告

c# - 如何添加/删除动态创建的用户控件

jquery - 获取动态id以在jquery ajax中显示信息