Exploring the realm of Vue.js, I am tasked with constructing a recursive Component renderer that transforms JSON into rendered Vue components.
The recursive rendering is functioning smoothly; however, the props passed to the createElement function (code below ;) ) are not accessible as props but are located inside the $vnode.data object. Any suggestions on what could be missing?
Illustrated below is the mock JSON structure being utilized:
{
"_id": "aslwi2",
"template": "NavigationBar",
"data": {},
"substructure": [
{
"_id": "assd2",
"template": "NavigationBarListItem",
"data": {
"title": "NavList Item 1"
}
},
{
"_id": "a2323uk",
"template": "NavigationBarListItem",
"data": {
"title": "NavList Item 2"
}
}
]
}
Implementation of Recursive Rendering Component:
const createComponent = function(node ,h){
if(!node || !node.template){
return;
}
let children = [];
if(node.substructure instanceof Array){
node.substructure.map( async childNode => {
const childComponent = createComponent(childNode, h);
children.push(childComponent);
});
}
return h(node.template, {xdata : clone(node.data)}, children.length > 0 ? children : null );
};
export default Vue.component('Structure', {
render: function(createElement){
if(!this.structure) return;
const component = createComponent(this.structure, createElement, registry);
console.log(component);
return component;
},
props: {
structure: {
type: Object
}
}
})
Dynamically Instantiated Components Example:
<!-- Component: NavBar -->
<template>
<div class="nav-bar">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
data: {
type: Object
}
}
}
</script>
<!-- Component: NavBarListItem -->
<template>
<div class="nav-bar-item">
{{title}}
</div>
</template>
<script>
export default {
data () {
return {
title : "default"
}
},
created() {
console.log('list item: ', this)
}
}
</script>
Upon inspecting the log within the list item component's created method, we observe the passed props present within the $vnode...