在element-ui的el-tree树形控件中默认获取选取当前选中id的方法是this.$refs.tree.getCheckedKeys();
但是如果子节点不是全部选中的话,父节点算不选中。
由于我们一般想要的是就算只选中一个直接点父节点以及其父辈都算选中,所以需要自己写逻辑。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>树形列表</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<style>
[v-cloak] {
display: none;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<el-tree
:data="rootData"
ref="rootTree"
show-checkbox
node-key="value"
default-expand-all>
</el-tree>
<button @click="getKeys">获取选中节点Key</button>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello',
rootData: [{"value":16,"label":"首页","parent":-1},{"value":17,"label":"用户列表","parent":-1},{"value":18,"label":"信息列表","parent":18},{"value":19,"label":"信息管理","parent":-1,"children":[{"value":20,"label":"个人信息","parent":19},{"value":21,"label":"修改信息","parent":19}]},{"value":22,"label":"资金数据","parent":-1,"children":[{"value":23,"label":"投资分布","parent":22},{"value":24,"label":"项目分布","parent":22},{"value":25,"label":"收支统计","parent":22}]},{"value":26,"label":"系统管理","parent":26,"children":[{"value":27,"label":"机构管理","parent":26},{"value":28,"label":"角色管理","parent":26},{"value":29,"label":"岗位管理","parent":26},{"value":30,"label":"用户管理","parent":26},{"value":31,"label":"系统菜单","parent":26}]},{"value":32,"label":"车辆管理","parent":-1,"children":[{"value":33,"label":"车辆信息","parent":32}]}]
},
methods: {
getKeys () {
var aKey = this.getCheckedKeys(this.rootData, this.$refs.rootTree.getCheckedKeys(), 'value');
console.log(aKey);
},
getCheckedKeys (data, keys, key) {
var res = [];
recursion(data, false);
return res;
// arr -> 树形总数据
// keys -> getCheckedKeys获取到的选中key值
// isChild -> 用来判断是否是子节点
function recursion (arr, isChild) {
var aCheck = [];
for ( var i = 0; i < arr.length; i++ ) {
var obj = arr[i];
aCheck[i] = false;
if ( obj.children ) {
aCheck[i] = recursion(obj.children, true) ? true : aCheck[i];
if ( aCheck[i] ) {
res.push(obj[key]);
}
}
for ( var j = 0; j < keys.length; j++ ) {
if ( obj[key] == keys[j] ) {
aCheck[i] = true;
if ( res.indexOf(obj[key]) == -1 ) {
res.push(obj[key]);
}
break;
}
}
}
if ( isChild ) {
return aCheck.indexOf(true) != -1;
}
}
}
}
})
</script>
</body>
</html>
getCheckedKeys函数用来获取选中的node-key指向的键值。