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

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>


回答:

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: ["......"]

}]

}]

}]

}]

}));

以上是 vue中这种树状结构数据,如何递归成dom节点 的全部内容, 来源链接: utcz.com/p/936557.html

回到顶部