简体   繁体   中英

VueJS - Render dynamically passed template in component

I am using VueJS 2 to build a drag-and-drop layout builder. 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. 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.

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
    :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.


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)
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)
3) There is a special uber-cool JS term for this which I simply do not know and that made my search attempts futile

You'd want to use slots instead.

In your ui-element component, define a slot like so:

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

Then you could pass in the draggable component like so:

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

Here's a very basic fiddle example of a slot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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