【问题标题】:Vue Component Props only available on $vnodeVue 组件道具仅在 $vnode 上可用
【发布时间】: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


    【解决方案1】:

    问题出在这里:

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

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

    要传递你会使用的道具props

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

    虽然我在努力遵循您的代码背后的意图,但看起来您可能还遇到了 NavBarListItem 未定义 title 属性的问题。你不能通过 title 除非它被定义为一个道具。在data 中定义它不是一回事。

    【讨论】:

    • 非常感谢!我认为第二个参数是将设置为道具的对象......现在它工作得很好。数据函数中的标题设置让我发疯并尝试不同的选项:)
    猜你喜欢
    • 2018-10-09
    • 2023-03-14
    • 2021-06-06
    • 2019-01-08
    • 2020-09-12
    • 2020-08-03
    • 2019-07-16
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多