gpt4 book ai didi

javascript - Vue 组件 Props 仅在 $vnode 上可用

转载 作者:行者123 更新时间:2023-12-02 22:55:03 27 4
gpt4 key购买 nike

我是 Vue.js 世界的新手,我必须构建一个递归组件渲染器,将 JSON 转换为渲染的 Vue 组件。

到目前为止,递归渲染工作得很好,除了我传递给 createElement 函数的 props(下面的代码;))不能用作 props,而是在 $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 中找到传递的 props...

Props available in $vnode but not as props

最佳答案

问题出在这里:

return h(node.template, {xdata : clone(node.data)}, ...

我不知道xdata是什么,但它不是您应该传递给h的东西。这些选项记录在 https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth .

要传递 Prop ,您可以使用 props

return h(node.template, {props : clone(node.data)}, ...

虽然我有点难以理解代码背后的意图,但看起来您可能还遇到 NavBarListItem 未定义 title 属性的问题。除非将 title 定义为 prop,否则无法传递它。在 data 中定义它并不是一回事。

关于javascript - Vue 组件 Props 仅在 $vnode 上可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58025471/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com