【发布时间】:2019-09-20 09:21:04
【问题描述】:
我是 Vue.js 世界的新手,我必须构建一个递归组件渲染器,将 JSON 转换为渲染的 Vue 组件。
到目前为止,递归渲染工作得很好,除了我传递给 createElement 函数的道具(下面的代码;))不能作为道具使用,而是在 $vnode.data 对象中。 有什么我想念的想法吗?
我使用的模拟 JSON 如下所示:
{
"_id": "aslwi2",
"template": "NavigationBar",
"data": {},
"substructure": [
{
"_id": "assd2",
"template": "NavigationBarListItem",
"data": {
"title": "NavList Item 1"
}
},
{
"_id": "a2323uk",
"template": "NavigationBarListItem",
"data": {
"title": "NavList Item 2"
}
}
]
}
我的递归渲染组件:
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
}
}
})
还有我的动态实例化组件:
<!-- 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>
在我的列表项组件中创建方法的日志中,我们在 $vnode 中找到传递的道具...
【问题讨论】:
标签: javascript vue.js