简体   繁体   English

VueJS - 在组件中呈现动态传递的模板

[英]VueJS - Render dynamically passed template in component

I am using VueJS 2 to build a drag-and-drop layout builder.我正在使用 VueJS 2 来构建拖放式布局构建器。 One of the requirements of that project is to be able to have some components that will allow for custom content to live inside (they will be just a wrapper around that content).该项目的要求之一是能够拥有一些允许自定义内容存在于其中的组件(它们将只是该内容的包装器)。 And to be really concrete, I am trying to pass in and render another drag-and-drop zone which is implemented in a draggable component.具体来说,我试图传入并渲染另一个在可拖动组件中实现的拖放区域

Basically, I want to pass a VueJS template to the component via a prop and have that template rendered inside of the component.基本上,我想通过 prop 将 VueJS 模板传递给组件,并在组件内部呈现该模板。 This is necessary because I do not want the UI to limit the needs of the developer and therefore need this to be really extensible.这是必要的,因为我不希望 UI 限制开发人员的需求,因此需要它是真正可扩展的。

In the following trivial example I would like the "ui-element" to render the content prop inside of it and use the other prop as a data input.在下面的简单示例中,我希望“ui-element”在其中呈现内容道具并将另一个道具用作数据输入。

<ui-element
    :content="<draggable :name="contentData"></draggable>"
    contentData="col1"
>
</ui-element>

Since just outputting the template will escape it, and v-html directive will treat it as regular HTML and not a template I am lost, not really sure how to get this done.由于只是输出模板会对其进行转义,并且 v-html 指令会将其视为常规 HTML 而不是模板,因此我迷路了,不确定如何完成此操作。


I spent about an hour or more googling but no luck.我花了大约一个小时或更长时间的谷歌搜索,但没有运气。 Which leaves me to three options:这让我有三个选择:
1) I'm the first one to need this complex use case (unlikely) 1)我是第一个需要这个复杂用例的人(不太可能)
2) Doing this is stupid on so many levels that no-one even bothered (if so, please let me know how to get this result in a smarter way) 2)这样做在很多层面上都是愚蠢的,甚至没有人打扰(如果是这样,请告诉我如何以更聪明的方式获得这个结果)
3) There is a special uber-cool JS term for this which I simply do not know and that made my search attempts futile 3)有一个特殊的超酷JS术语,我根本不知道,这让我的搜索尝试徒劳无功

You'd want to use slots instead.您想改用插槽

In your ui-element component, define a slot like so:在您的ui-element组件中,定义一个插槽,如下所示:

<template>
  <div>
    <slot name="content"></slot>
  </div>
</template>

Then you could pass in the draggable component like so:然后你可以像这样传入draggable组件:

<ui-element contentData="col1">
  <draggable :name="contentData" slot="content"></draggable>
</ui-element>

Here's a very basic fiddle example of a slot.这是插槽的一个非常基本的小提琴示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM