0
다음 데이터를 병합하려고하지만 vue 메서드의 재귀 함수가 제대로 작동하지 않습니다. 내가 디버깅하는 동안 나는 일단 reduce 함수를 입력하면 'this'변수가 다른 변수 (원래 vue 구성 요소)로 변경된다는 것을 알게되었습니다.vue js 중첩 부모 - 자식 개체를 재귀 적으로 병합합니다.
{
"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/ 내 REPO입니다. 당신의 뷰에서 this
을 유지하는 대신 function
키워드
// 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>