【Vue.js---iView---Tree 树形控件】树的搜索,输入节点名称,选中该节点并展开它的父节点

一、最终效果:

 二、代码:

1.vue文件

<template>
  <div>
    <Row>
      <Col span="24">
        <Input
          prefix="ios-search"
          v-model="searchName"
          clearable
          placeholder="请输入名称"
          @on-enter="searchTree"
        />
      </Col>
      <Col span="24">
        <Tree :data="treeData" @on-select-change="selectChange"></Tree>
      </Col>
    </Row>
  </div>
</template>

<script>
    import { listToTree } from "../../../libs/listToTree.js";
    export default {
        data() {
            return {
                treeRawData: [
                    //后端返回的数据
                    { title: "地球", id: "1", parentId: "0" },
                    { title: "中国", id: "2", parentId: "1" },
                    { title: "上海", id: "3", parentId: "2" },
                    { title: "徐汇", id: "4", parentId: "3" },
                    { title: "美国", id: "5", parentId: "1" },
                    { title: "纽约", id: "6", parentId: "5" },
                ],
                treeData: [], //前端处理后的数据
                searchName: "", //输入框绑定的数据
                currentId: "", //需要选中的节点id
            };
        },
        mounted() {
            this.treeData = listToTree(this.treeRawData); //将后端返回的list数据转化为树结构
        },
        methods: {
            //输入节点名称后按回车健搜索
            searchTree() {
                let exist = false;
                for (var i = 0; i < this.treeRawData.length; i++) {
                    if (this.treeRawData[i].title.indexOf(this.searchName) !== -1) {
                        //在树中存在
                        exist = true;
                        this.currentId = this.treeRawData[i].id;

                        /*需要重新获取treeRawData,不然会出现这种情况:数据是对的,但是视图渲染不出来,导致没有搜索结果*/
                        this.treeRawData = [
                            { title: "地球", id: "1", parentId: "0" },
                            { title: "中国", id: "2", parentId: "1" },
                            { title: "上海", id: "3", parentId: "2" },
                            { title: "徐汇", id: "4", parentId: "3" },
                            { title: "美国", id: "5", parentId: "1" },
                            { title: "纽约", id: "6", parentId: "5" },
                        ];
                        this.treeData = listToTree(this.treeRawData);
                        /*需要重新获取treeRawData,不然会出现这种情况:数据是对的,但是视图渲染不出来,导致没有搜索结果*/

                        this.treeData = this.fineCurrentIdRecursive(this.treeData);
                        break;
                    } else if (!exist && i === this.treeRawData.length - 1) {
                        //在树中不存在
                        this.$Message.error("无搜索结果");
                    }
                }
            },

            //通过节点id选中树中节点并展开它的父节点-递归方式
            fineCurrentIdRecursive(list) {
                for (var i = 0; i < list.length; i++) {
                    if (list[i].id === this.currentId) {
                        list[i].selected = true; //如果节点id等于currentId,则选中该节点
                        break;
                    } else {
                        if (list[i].children && list[i].children.length > 0) {
                            list[i].children = this.fineCurrentIdRecursive(list[i].children); //找不到想要的节点则继续找孩子的(递归)
                            for (var j = 0; j < list[i].children.length; j++) {
                                if (list[i].children[j].selected || list[i].children[j].expand) {
                                    list[i].expand = true; //如果子节点(末端节点)选中或者子节点(非末端节点)展开,则展开该子节点的父节点
                                    break;
                                }
                            }
                        }
                    }
                }
                return list;
            },

            // 点击节点文字展开收起
            selectChange(data, selectedNode) {
                this.$set(selectedNode, "expand", !selectedNode.expand);
            }
        }
    };
</script>

2.引入的listToTree.js文件

//将后端返回的list数据转化为树结构
export const listToTree = (list) => {
    var arr = []
    let items = {}
    var idsStr = ''
    // 获取每个节点的直属子节点(是直属,不是所有子节点)
    for (let i = 0; i < list.length; i++) {
        let key = list[i].parentId
        if (items[key]) {
            items[key].push(list[i])
        } else {
            items[key] = []
            items[key].push(list[i])
        }
        idsStr += idsStr === '' ? list[i].id : ',' + list[i].id
    }
    for (var key in items) {
        if (idsStr.indexOf(key) === -1) {//找到最大的父节点key
            arr=formatTree(items, key)
        }
    }
    delete arr[0].parentId
    return arr
}
function formatTree(items, parentId) {
    let result = []
    if (!items[parentId]) {
        return result
    }
    for (let t of items[parentId]) {
        t.children = formatTree(items, t.id)//递归获取children
        result.push(t)
    }
    return result
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Ant-Design-Vue的Tree组件提供了add方法来新增节点和remove方法来删除节点。以下是示例代码: ```html <template> <a-tree :tree-data="treeData" :draggable="true" :block-node="true" :show-line="true" :default-expanded-keys="defaultExpandedKeys" @select="onSelect"> <template #title="{ key, title }"> <span> {{ title }} <a @click.stop="addNode(key)">Add</a> <a @click.stop="removeNode(key)">Delete</a> </span> </template> </a-tree> </template> <script> export default { data() { return { treeData: [ { title: 'Parent 1', key: '0-0', children: [ { title: 'Child 1', key: '0-0-0' }, { title: 'Child 2', key: '0-0-1' } ] } ], defaultExpandedKeys: ['0-0'] } }, methods: { addNode(parentKey) { const newNode = { title: 'New Node', key: `${parentKey}-${this.treeData.length}` } this.$set(this.treeData.find(node => node.key === parentKey), 'children', [...this.treeData.find(node => node.key === parentKey).children, newNode]) }, removeNode(key) { const parentKey = key.split('-').slice(0, -1).join('-') this.$set(this.treeData.find(node => node.key === parentKey), 'children', this.treeData.find(node => node.key === parentKey).children.filter(node => node.key !== key)) }, onSelect(selectedKeys) { console.log(selectedKeys) } } } </script> ``` 在这个示例中,我们使用了Tree组件自带的title slot来添加按钮。点击Add按钮会调用addNode方法,该方法会在选定节点下添加一个新节点。点击Delete按钮会调用removeNode方法,该方法会删除选定节点。这两个方法都使用了Vue的$set方法来更新数据。同时,我们也监听了Tree组件的select事件来打印出所选中节点

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悄羊羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值