用uniapp写一个table联动
时间: 2024-05-05 14:21:06 浏览: 8
好的,下面是一个简单的示例:
```html
<template>
<view>
<view class="picker-view">
<picker
mode="selector"
:range="{{ table1 }}"
:value="{{ index1 }}"
@change="handleTable1Change"
>
<view class="picker">
{{ table1[index1].name }}
</view>
</picker>
<picker
mode="selector"
:range="{{ table2 }}"
:value="{{ index2 }}"
@change="handleTable2Change"
>
<view class="picker">
{{ table2[index2].name }}
</view>
</picker>
</view>
</view>
</template>
<script>
export default {
data() {
return {
table1: [
{ name: "A", children: ["A1", "A2", "A3"] },
{ name: "B", children: ["B1", "B2", "B3"] },
{ name: "C", children: ["C1", "C2", "C3"] }
],
table2: [],
index1: 0,
index2: 0
};
},
methods: {
handleTable1Change(e) {
const index1 = e.detail.value;
const table1Item = this.table1[index1];
const table2 = table1Item.children.map(name => ({ name }));
this.table2 = table2;
this.index1 = index1;
this.index2 = 0;
},
handleTable2Change(e) {
this.index2 = e.detail.value;
}
},
mounted() {
this.handleTable1Change({ detail: { value: 0 } });
}
};
</script>
<style>
.picker-view {
display: flex;
align-items: center;
justify-content: space-around;
height: 100vh;
}
.picker {
font-size: 28px;
color: #007aff;
}
</style>
```
这个示例展示了两个联动的 picker 组件,表格1和表格2。当用户在表格1中选择一个项目时,表格2将根据所选项目的子项进行更新。这是通过监听表格1 picker 的 change 事件来实现的。在事件处理程序中,我们获取所选项目,并使用它的子项更新表格2。然后,我们将表格1和表格2的索引重置为默认值。当用户在表格2中选择一个项目时,我们只是更新表格2的索引。最后,在组件挂载时,我们调用 handleTable1Change 方法来初始化表格1和表格2。