编译动态添加到DOM的Vue组件

时间:2018-03-26 05:04:59

标签: javascript vue.js vuejs2

我们有一个使用Vue作为前端框架的网络应用程序。

此网络应用程序有一个文本编辑器,作为文本编辑器功能的一部分,它会将自定义HTML添加到可编辑区域(contenteditable div。)

编辑器可以添加作为Vue组件的HTML,但我需要一些方法在将Vue组件插入DOM之前/之后对其进行编译。

例如,我们假设我们有一个contenteditable div,如下所示:

<div contenteditable="true">
    <p>Some text</p>
</div>

现在,在用户操作上,在<p>标记之后,编辑器将插入Vue组件。

<div contenteditable="true">
    <p>Some text</p>
    <custom-gallery></custom-gallery>
</div>

<custom-gallery></custom-gallery>是Vue组件。我如何执行&#39;这个组件所以它呈现HTML,事件处理程序等?

我的一个想法是插入一个像:

这样的元素
<div contenteditable="true">
    <p>Some text</p>
    <div class="custom-gallery"></div>
</div>

然后执行:

import Vue from 'vue'
import CustomGallery from './path/to/components/CustomGallery.vue'

new Vue({
    el: document.querySelector(".custom-gallery"),
    render: h => h(CustomGallery)
})

那会是最好的方法吗?如果它已经在Vue应用程序中,它会起作用吗?

2 个答案:

答案 0 :(得分:1)

将Vue组件插入DOM后,实例化Vue实例:

$('#ControlContainer').append("<vueComponent id='component1'></vueComponent>");

var vmComponent = new Vue({
            el: '#component1',
            mounted: function () {
            }
        });

答案 1 :(得分:0)

我建议您只使用动态组件,并在首次渲染页面时将其放在您的contenteditable div中。

<div contenteditable="true">
    <component :is="myComponent"></component>
</div>

myComponent可以是一个函数,您可以将组件名称传递给它,甚至可以使用不同的组件动态切换它。但是在您的情况下,您可以将其作为prop以false或null值开始,然后当您希望初始化gallery组件时,调用一个函数来设置名称。

data:{
   component: false,
},
   methods: {
     setComponent(){
        this.component = 'custom-gallery';
}

这是一个基本工作示例https://jsfiddle.net/skribe/3d15L39t/7/

的jfiddle

有关动态组件的更多信息https://vuejs.org/v2/guide/components.html#Dynamic-Components

相关问题