首页 > 解决方案 > 如何在选择标签选项中正确显示数组子项

问题描述

我有用于选择选项的带有树视图的自定义数据数组:

[
  {
    "id": 1,
    "name": "Parent 1",
    "children": [
      {
        "id": 2,
        "name": "Parent 1 - Children 1"
      },
      {
        "id": 3,
        "name": "Parent 1 - Children 2"
      }
    ]
  },
  {
    "id": 4,
    "name": "Parent 2",
    "children": []
  },
  {
    "id": 5,
    "name": "Parent 3",
    "children": [
      {
        "id": 6,
        "name": "Parent 3 - Children 1",
        "children": [
          {
            "id": 7,
            "name": "Parent 3 -> Children 1 -> Children 1"
          },
          {
            "id": 8,
            "name": "Parent 3 -> Children 1 -> Children 2"
          },
        ]
      }
    ]
  }
]

我如何在<select>标签选项中显示我的树视图数组,如下所示:

<select>
  <option value="1">Parent 1</option>
  <option value="2">--Children 1</option>
  <option value="3">--Children 2</option>
  <option value="4">Parent 2</option>
  <option value="5">Parent 3</option>
  <option value="6">--Children 1</option>
  <option value="7">----Children 1</option>
  <option value="8">----Children 2</option>
</select>

我在逻辑上无法解决这个问题。我通常在 Vue.js 中以这种方式显示选项:

<select class="form-control">
  <option v-for="option in selectOptions">{{option}}</option>
</select>

标签: javascriptvue.jsvuejs2frontendnuxt.js

解决方案


像这样的东西?

new Vue({
  el: '#app',
  data() {
    return {
      options: getData(),
      selected: null
    }
  },
  computed: {
    selectOptions() {
      const tree = this.options
      const flat = []

      add(this.options, '')

      return flat

      function add(nodes, prefix) {
        nodes.forEach(node => {
          flat.push({
            ...node,
            name: prefix + node.name
          })

          add(node.children || [], prefix + '- ')
        })
      }
    }
  }
})

function getData() {
  return [{
      "id": 1,
      "name": "Parent 1",
      "children": [{
          "id": 2,
          "name": "Parent 1 - Children 1"
        },
        {
          "id": 3,
          "name": "Parent 1 - Children 2"
        }
      ]
    },
    {
      "id": 4,
      "name": "Parent 2",
      "children": []
    },
    {
      "id": 5,
      "name": "Parent 3",
      "children": [{
        "id": 6,
        "name": "Parent 3 - Children 1",
        "children": [{
            "id": 7,
            "name": "Parent 3 -> Children 1 -> Children 1"
          },
          {
            "id": 8,
            "name": "Parent 3 -> Children 1 -> Children 2"
          },
        ]
      }]
    }
  ]
}
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="app">
  <select v-model="selected">
    <option v-for="option in selectOptions" :value="option.id">{{ option.name }}</option>
  </select>
  <p>Selected: {{ selected }}</p>
</div>

我正在使用计算属性来保存树的扁平版本,并通过一些递归来进行扁平化。


推荐阅读