javascript - 如何在选择标签选项中正确显示数组子项
问题描述
我有用于选择选项的带有树视图的自定义数据数组:
[
{
"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>
解决方案
像这样的东西?
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>
我正在使用计算属性来保存树的扁平版本,并通过一些递归来进行扁平化。
推荐阅读
- css - 个人资料图片和输入在移动视图中消失
- python - Python:ValueError:int()的无效文字,if else条件语句的语句中的基数为10
- jax-rs - 服务器发送事件 JAX-RS
- azure-devops - 在 Azure DevOps 中,如何自动将工作项从一个状态移动到另一个状态?
- c++ - 从 Visual Studio 部署非常小的应用程序的困难
- python - kivy 应用程序中的错误:object.__init__() 仅采用一个参数(要初始化的实例)
- c++ - 没有这样的文件或目录collect2.exe:错误:ld 返回 1 退出状态
- flutter - 如何突出显示搜索结果中的匹配项
- css - 预选选项在页面加载时突出显示为灰色,希望它为蓝色
- reactjs - React Hooks 中关于 setState 回调的一些混淆