vue中这种树状结构数据,如何递归成dom节点

在vue中数据是这样的类型

{
    name:'A',
    child:{
        name:'B',
        child:{
            name:'C',
            child: {
                name:'D',
                child:......
            }
        }
    }
}

如何用这种数据递归出元素节点的dom

<div>
    <span>A</span>
    <div>
        <span>B</span>
        <div>
            <span>C</span>
            <div>
                <span>D</span>
                <div>.....</div>
            </div>
        </div>
    </div>
</div>
阅读 2.8k
2 个回答

vue 递归组件,在组件内部使用自己这个组件=。=

<template>
  <div>
    <span>{{ child.name }}</span>
    <tree
      v-for="(_child, key) in child.child"
      :key="key"
      :child="_child"
    >
  </div>
</template>
<script>
export default {
 name: 'tree',
 props: {
   child: [Object]
 }
}
</script>
function render(tree) {
    var dom = null;
    if (typeof tree === "string") {
        dom = document.createTextNode(tree);
    } else if (typeof tree === "object" && tree) {
        dom = document.createElement(tree.name);
        if (tree.child instanceof Array) {
            for (var i = 0; i < tree.child.length; ++i) {
                var node = render(tree.child[i]);
                if (node) dom.appendChild(node);
            }
        }
    }
    return dom;
}
console.log(render({
    name: "div",
    child: [{
        name: "span",
        child: ["A"]
    },
    {
        name: "div",
        child: [{
            name: "span",
            child: ["B"]
        },
        {
            name: "div",
            child: [{
                name: "span",
                child: ["C"]
            },
            {
                name: "div",
                child: [{
                    name: "span",
                    child: ["D"]
                },
                {
                    name: "div",
                    child: ["......"]
                }]
            }]
        }]
    }]
}));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏