如何在SELECT标签选项中正确显示阵列



我有一个自定义数据数组,带有treeview的选择选项:

[
  {
    "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>标签选项中显示我的TreeView Array:

<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>

类似的东西?

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>

我正在使用计算的属性来容纳树木的扁平版本,并有点递归进行扁平。

相关内容

  • 没有找到相关文章

最新更新