项目开发中在使用到 tree 树形控件实现单选功能,element-ui 官方给出来复选事件,并没有单选操作,自己就研究了一下,代码如下:
1、template 代码中:
<el-tree :data="treeData" :props="defaultProps" node-key="id" ref="treeForm"
show-checkbox check-strictly @check-change="handleNodeClick"> </el-tree>
2、data 代码中:
data() { return { checkedId: '', treeData: [{ id: 1, label: '一级 1', children:
[{ id: 4, label: '二级 1-1', children: [{ id: 9, label: '三级 1-1-1' }, { id: 10,
label: '三级 1-1-2' }] }] }, { id: 2, label: '一级 2', children: [{ id: 5, label:
'二级 2-1' }, { id: 6, label: '二级 2-2' }] }, { id: 3, label: '一级 3', children: [{
id: 7, label: '二级 3-1' }, { id: 8, label: '二级 3-2' }] }], defaultProps: {
children: 'children', label: 'label' } } }
3、methods 代码中:
handleNodeClick(data, checked, node) { if(checked === true) { this.checkedId =
data.id; this.$refs.treeForm.setCheckedKeys([data.id]); } else { if
(this.checkedId == data.id) { this.$refs.treeForm.setCheckedKeys([data.id]); }
} }