vue主从表实现
Vue 主从表实现方法
基础数据结构设计
主表数据通常是一个数组,每个主表项包含唯一标识符(如id)和关联的子表数据字段:

data() {
return {
masterData: [
{ id: 1, name: '主项1', details: [{ subId: 1, content: '子项1' }] },
{ id: 2, name: '主项2', details: [] }
],
activeMasterId: null
}
}
主表渲染
使用v-for循环渲染主表,通过点击事件设置当前激活的主表ID:

<ul>
<li v-for="item in masterData"
:key="item.id"
@click="activeMasterId = item.id"
:class="{ active: activeMasterId === item.id }">
{{ item.name }}
</li>
</ul>
从表动态显示
根据当前激活的主表ID过滤显示对应的子表数据:
<div v-if="activeMasterId">
<table>
<tr v-for="(detail, index) in getCurrentDetails()" :key="index">
<td>{{ detail.content }}</td>
</tr>
</table>
</div>
数据联动方法
添加计算属性或方法获取当前主表对应的子表数据:
methods: {
getCurrentDetails() {
const master = this.masterData.find(item => item.id === this.activeMasterId)
return master ? master.details : []
}
}
完整组件示例
<template>
<div class="master-detail">
<div class="master-list">
<h3>主表</h3>
<ul>
<li v-for="item in masterData"
@click="selectMaster(item.id)"
:class="{ active: activeMasterId === item.id }">
{{ item.name }}
</li>
</ul>
</div>
<div class="detail-list" v-if="activeMasterId">
<h3>子表</h3>
<button @click="addDetail">添加子项</button>
<table>
<tr v-for="(detail, index) in currentDetails" :key="detail.subId">
<td>{{ detail.content }}</td>
<td><button @click="removeDetail(index)">删除</button></td>
</tr>
</table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
masterData: [
{ id: 1, name: '项目A', details: [
{ subId: 101, content: '子项A1' },
{ subId: 102, content: '子项A2' }
]},
{ id: 2, name: '项目B', details: [] }
],
activeMasterId: null
}
},
computed: {
currentDetails() {
const master = this.masterData.find(item => item.id === this.activeMasterId)
return master ? master.details : []
}
},
methods: {
selectMaster(id) {
this.activeMasterId = id
},
addDetail() {
const master = this.masterData.find(item => item.id === this.activeMasterId)
if (master) {
const newId = Math.max(...master.details.map(d => d.subId), 0) + 1
master.details.push({
subId: newId,
content: `新子项${newId}`
})
}
},
removeDetail(index) {
const master = this.masterData.find(item => item.id === this.activeMasterId)
if (master) {
master.details.splice(index, 1)
}
}
}
}
</script>
<style>
.master-detail { display: flex; }
.master-list { width: 200px; }
.detail-list { flex: 1; }
.active { background-color: #eee; }
</style>
关键实现要点
- 数据双向绑定:主表和子表数据都通过Vue的响应式系统管理
- 状态管理:使用
activeMasterId跟踪当前选中的主表项 - 组件通信:子表操作通过方法直接修改主表数据中的对应数组
- 唯一标识:主表和子表都需要稳定的key标识(如
id和subId)
进阶优化方向
- 使用Vuex管理复杂状态
- 添加表单验证功能
- 实现本地缓存或API数据持久化
- 添加分页加载功能
- 使用动态组件实现更灵活的布局






