Reputation: 1243
I wrote a wrapper directive that utilizes vue's Render function. Inside the render function all it does is:
render: function(createElement) {
const compiled = Vue.compile(this.$props.template);
return compiled.render.call(this, createElement);
}
I'm using like:
<Render v-for="item in itemsToRender" :key="item.id" />
This works for native html elements:
const itemsToRender = ['<p>test</p>', '<h1>HELLO</h1>'];
However if I pass in my own custom directive like
<my-directive></my-directive>
Then vue will complain about unknown components. This is probably because I don't have the custom directive imported/required in the render directive's context. Is there a work around for this? The reason I need to have this wrapper directive do the compile is because libraries like vue.Draggable, rely on 'v-for' to reorder the list elements. However, I want to be able to have different components be draggable, which is why i'm passing just templates to compile into the v-for.
Upvotes: 0
Views: 843
Reputation: 4057
You can use the component tag. Check out: https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components
I have made an example here: https://codepen.io/bergur/pen/jjwzEq
The flow is roughly this:
<component>
tag to render themHere is the code
new Vue({
name: 'main',
el: '#main',
components: {
CompA,
CompB
},
data() {
return {
header: 'Multiple components',
itemsToRender: [CompA, CompB]
}
},
template: `
<div>
{{ header }}
<component v-for="item in itemsToRender" :is="item" />
</div>`
})
Upvotes: 1