Reputation: 472
I am building a system that can generate HTML from JSON.
The following JSON
"type": "span",
"content": [
{
"type": "span",
"content": [
{
"type": "div",
"content": []
}
]
}
]
Should generate The following html
<span>
<span>
<div></div>
</span>
</span>
I have made this to convert the JSON
export default {
name: 'HTMLElement',
props: {
data: {
type: Array,
default: []
}
},
render(createElement) {
return createElement(
this.data.type,
createElement(
HTMLElement,
{
props: {
data: this.data.content
}
}
)
);
}
}
The propertie data is the JSON only than parsed to a Object
When I am running this code I get the following error
Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
Has anyone any idea of a better solution or a fix to this situation ?
Thank you in advance,
Jeroen
Upvotes: 0
Views: 84
Reputation: 135772
You seem to be in need of a recursive function. See the buildElement
method below. It is used in the render()
and works as you describe:
Vue.component('html-element', {
name: 'HTMLElement',
props: {
data: {
type: Object,
default: {type: 'div'}
}
},
render(createElement) {
return this.buildElement(createElement, this.data)
},
methods: {
buildElement(createElementFunction, data) {
return createElementFunction(
data.type, (data.content || []).map(c => this.buildElement(createElementFunction, c))
);
}
}
});
new Vue({
el: '#app',
data: {
elementData: {
"type": "span",
"content": [{
"type": "span",
"content": [{
"type": "div",
"content": []
}]
}]
}
}
})
span { display: inline-block; border: 1px solid red; width: 50px }
<script src="https://unpkg.com/vue"></script>
<span>
<span>
<div></div>
</span>
</span>
<hr>
<div id="app">
<html-element :data="elementData"></html-element>
</div>
Upvotes: 1