【发布时间】:2018-06-07 20:17:42
【问题描述】:
我正在尝试展平以下数据,但显然我在 vue 方法中的递归函数无法正常工作。在调试时,我注意到一旦它进入 reduce 函数,“this”变量就会变成其他东西(最初是 vue 组件)。
{
"id":1,
"level":"1",
"text":"Sammy",
"type":"Item",
"children":[
{
"id":11,
"level":"2",
"text":"Table",
"type":"Item",
"children":[
{
"id":111,
"level":"3",
"text":"Dog",
"type":"Item",
"children":null
},
{
"id":112,
"level":"3",
"text":"Cat",
"type":"Item",
"children":null
}
]
},
{
"id":12,
"level":"2",
"text":"Chair",
"type":"Item",
"children":[
{
"id":121,
"level":"3",
"text":"Dog",
"type":"Item",
"children":null
},
{
"id":122,
"level":"3",
"text":"Cat",
"type":"Item",
"children":null
}
]
}
]
}
想要的结果
{
"id":1,
"level":"1",
"text":"Sammy",
"type":"Item",
"children":[]
}
{
"id":11,
"level":"2",
"text":"Table",
"type":"Item",
"children":[]
}
...
https://jsfiddle.net/hr8dhy8n/11/ 这是我的仓库。
// https://stackoverflow.com/q/47961578/3397771
var data =[
{
"id":1,
"level":"1",
"text":"Sammy",
"type":"Item",
"children":[
{
"id":11,
"level":"2",
"text":"Table",
"type":"Item",
"children":[
{
"id":111,
"level":"3",
"text":"Dog",
"type":"Item",
"children":null
},
{
"id":112,
"level":"3",
"text":"Cat",
"type":"Item",
"children":null
}
]
},
{
"id":12,
"level":"2",
"text":"Chair",
"type":"Item",
"children":[
{
"id":121,
"level":"3",
"text":"Dog",
"type":"Item",
"children":null
},
{
"id":122,
"level":"3",
"text":"Cat",
"type":"Item",
"children":null
}
]
}
]
}
]
// define the item component
Vue.component('item', {
methods: {
flattenInformation: function(a, b) {
return a.reduce(function (p, c) {
!!c.children ? (p.push(c), this.flattenInformation(c.children, p), c.children = []) : p.push(c);return p;
}, b);
},
getLengthNow (model) {
var list = [];
list.push(model);
var flatten = this.flattenInformation(list,[]);
}
},
props: ['model'],
template: '#item-template'
})
// boot up the demo
var demo = new Vue({
data: {
nestedData: data
},
el: '#demo'
});
<!-- item template -->
<script type="text/x-template" id="item-template">
<template>
{{this.getLengthNow(this.model)}}
</template>
</script>
<!-- the demo root element -->
<ul id="demo">
<item
class="item"
:model="nestedData[0]">
</item>
</ul>
【问题讨论】:
标签: javascript recursion vue.js