简体   繁体   English

Vue:如何在表中显示嵌套对象数组的每个“叶子”?

[英]Vue: How to display each “leaf” of an array of nested objects in a table?

I have an array that looks like this: 我有一个看起来像这样的数组:

var arr = [{
  text: '1'
}, {
  text: '2'
  children: [{
    text: '2.1'
  }]
}, {
  text: '3',
  children: [{
    text: '3.1'
  }, {
    text: '3.2',
    children: [{
      text: '3.2.1'
    }, {
      text: '3.2.2'
    }]
  }]
}];

I want to display only the "leafs" of this array in a table, while showing the parents of the leafs. 我只想在表中显示此数组的“叶子”,同时显示叶子的父母。 I want to generate the following HTML: 我想生成以下HTML:

<table>
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>2 | 2.1</td>
  </tr>
  <tr>
    <td>3 | 3.1</td>
  </tr>
  <tr>
    <td>3 | 3.2 | 3.2.1</td>
  </tr>
  <tr>
    <td>3 | 3.2 | 3.2.2</td>
  </tr>
</table>

I tried the following, but it doesn't work because the <section> s are interspersed with the <tr> s. 我尝试了以下操作,但由于<section>插入了<tr> ,因此无法正常工作。

<section v-for="parent in arr">
  <tr v-if="!parent.children">
    <td>{{ parent.text }}</td>
  </tr>
  <section v-if="parent.children" v-for="child in parent.children">
    <tr v-if="!child.children">
      <td>{{ parent.text + ' | ' + child.text }}</td>
    </tr>
    <tr v-if="child.children" v-for="grandchild in child.children">
      <td>{{ parent.text + ' | ' + child.text + ' | ' + grandchild.text }}</td>
    </tr>
  </section>
</section>

In Vue, it's always better to try and simplify your data structure to cater to your display needs than to try and find a roundabout way of displaying your data using directives in the template. 在Vue中,尝试简化数据结构以满足显示需求总是比尝试使用模板中的指令找到一种回旋方式显示数据更好。

Usually, the best way to simplify your data is via computed properties. 通常,简化数据的最佳方法是通过计算属性。 As @RoyJ suggested, you can make a computed property which would recursively generate a flattened array from your object's tree structure, and then reference that computed in the template instead. 正如@RoyJ所建议的那样,您可以创建一个计算属性,该属性将从对象的树结构中递归地生成一个扁平化的数组,然后引用在模板中计算出的那个数组。

Here's how I would do it: 这是我的处理方式:

 new Vue({ el: '#app', data() { return { arr: [{ text: '1' }, { text: '2', children: [{ text: '2.1' }] }, { text: '3', children: [{ text: '3.1' }, { text: '3.2', children: [{ text: '3.2.1' }, { text: '3.2.2' }] }] }] } }, computed: { flatArr() { let flatArr = []; let addToFlatArr = ({ items, base }) => { items.forEach((item) => { let { text, children } = item; let val = (base || '') + text; if (children) { addToFlatArr({ items: children, base: val + ' | '}) } else { flatArr.push(val); } }) }; addToFlatArr({ items: this.arr }); return flatArr; } }, }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script> <div id='app'> <table> <tr v-for="item in flatArr"> <td>{{ item }}</td> </tr> </table> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM