1.实现思路
利用el-tree组件的check-strictly
属性,动态更改父节点和子节点的强关联关系;
1.当数据过滤后,将
check-strictly
设置为true
,解除父子节点强关联关系; 2.父节点选中时,通过check
事件,递归获取子节点,并将显示的节点属性设置为父节点一样; 3.重置check-strictly
为false
,使父子节点强关联 4.等待dom更新后,获取所有选中节点,调用setCheckedNodes
选中所有节点。
2.直接上demo
提供了html搭配cdn的demo,新建一个html就可以直接查看效果啦!
xml
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
rel="stylesheet"
href="https://unpkg.com/element-ui@2.15.14/lib/theme-chalk/index.css"
/>
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui@2.15.14/lib/index.js"></script>
</head>
<body>
<div id="app">
<el-input placeholder="输入关键字进行过滤" v-model="filterText">
</el-input>
<el-tree
class="filter-tree"
:data="data"
:props="defaultProps"
node-key="id"
default-expand-all
show-checkbox
:check-strictly="checkStrictly"
:filter-node-method="filterNode"
@check="handleCheck"
ref="tree"
>
</el-tree>
</div>
</body>
<script>
var Main = {
watch: {
filterText(val) {
this.checkStrictly = true;
this.$refs.tree.filter(val);
},
},
methods: {
filterNode(value, data) {
if (!value) return true;
return data.label.indexOf(value) !== -1;
},
handleCheck(data) {
let node = this.$refs.tree.getNode(data);
let checked = node.checked;
// 选中当前过滤过后的节点机器所有子节点
this.setNodeSelectStatus(node, checked);
this.checkStrictly = false;
// 选中的节点数据
const selectedChildNodes = this.$refs.tree.getCheckedNodes(true);
this.$nextTick(() => {
// 重新选中所有节点,因父子节点强关联,所以会同步父节点选择状态
this.$refs.tree.setCheckedNodes(selectedChildNodes);
});
},
setNodeSelectStatus(node, selected) {
this.$refs.tree.setChecked(node, selected, false);
if (node.childNodes && node.childNodes.length > 0) {
node.childNodes.forEach((childNode) => {
if (childNode.visible) {
this.setNodeSelectStatus(childNode, selected);
}
});
}
},
},
data() {
return {
filterText: "",
checkStrictly: false,
data: [
{
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",
},
};
},
};
var Ctor = Vue.extend(Main);
new Ctor().$mount("#app");
</script>
</html>