vue2 el-table中的<treeselect>选择一条数据后在选择框里显示上级名称+本级名称,下拉框的内容不组合
时间: 2025-03-22 19:08:22 浏览: 29
### 解决方案
在 Vue2 中使用 `el-table` 和 `<treeselect>` 组件时,可以通过自定义列渲染来实现选中后显示上级名称与当前级别名称的组合效果,同时保持下拉列表内容不变。以下是具体实现方式:
#### 自定义列渲染
可以利用 `el-table-column` 的插槽机制(slot-scope),结合 `<treeselect>` 的值绑定逻辑,动态生成所需的显示内容。
```vue
<template>
<div>
<!-- Table -->
<el-table :data="tableData">
<el-table-column label="名称" prop="name"></el-table-column>
<el-table-column label="类别" width="300">
<template slot-scope="scope">
<treeselect
v-model="scope.row.categoryId"
:options="categoryOptions"
@select="onSelect($event, scope.row)"
placeholder="请选择类别"
/>
{{ getDisplayName(scope.row.parentName, scope.row.currentName) }}
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
export default {
components: { Treeselect },
data() {
return {
tableData: [
{ name: '项目A', categoryId: null, parentName: '', currentName: '' },
{ name: '项目B', categoryId: null, parentName: '', currentName: '' },
],
categoryOptions: [
{ id: 1, label: '分类1' },
{ id: 2, label: '分类2', children: [{ id: 3, label: '子分类2-1' }] },
],
};
},
methods: {
onSelect(selectedNode, row) {
const parentNode = this.findParent(this.categoryOptions, selectedNode.id);
row.parentName = parentNode ? parentNode.label : '';
row.currentName = selectedNode.label;
},
findParent(tree, nodeId) {
for (const node of tree) {
if ('children' in node) {
const childMatch = this.findInChildren(node.children, nodeId);
if (childMatch) return childMatch || node;
}
if (node.id === nodeId) return node;
}
return null;
},
findInChildren(children, nodeId) {
if (!children) return null;
for (const child of children) {
if (child.id === nodeId) return child;
if ('children' in child) {
const match = this.findInChildren(child.children, nodeId);
if (match) return match;
}
}
return null;
},
getDisplayName(parentName, currentName) {
return `${parentName}${parentName ? '/' : ''}${currentName}`;
},
},
};
</script>
```
---
#### 关键点解析
1. **Treeselect 值绑定**
使用 `v-model` 将 `<treeselect>` 的值绑定到对应行的数据字段上,例如 `categoryId`[^1]。
2. **Slot-Scope 动态渲染**
利用 `el-table-column` 的 `slot-scope` 属性,可以在单元格内嵌入复杂的组件结构,并通过事件监听器捕获用户交互行为[^4]。
3. **父节点查找**
定义辅助函数 `findParent` 来递归遍历树形结构,找到所选节点对应的父节点信息。
4. **显示名拼接**
提供一个工具方法 `getDisplayName`,用于将父节点名称和当前节点名称按指定格式拼接成最终显示字符串。
5. **表单更新同步**
当用户选择某个选项时,触发回调函数 `@select` 更新该行的相关属性(如 `parentName` 和 `currentName`)。
---
#### 注意事项
- 如果需要支持多级层次关系,则需扩展 `findParent` 函数以处理更深层次的父子链路。
- 确保传给 `<treeselect>` 的 `options` 数据是一个合法的树状数组结构[^2]。
- 需要引入并注册 `@riophae/vue-treeselect` 及其样式文件[^3]。
---
###
阅读全文
相关推荐

















