When the el-tree has no check box, the realization of the function of keeping the expanded state after selecting, currentNodeKey highlighting, positioning, and refreshing

chance

A problem encountered when using the el-tree without a selection box is that when a row of data is clicked, there will be a background color, but when the mouse is clicked elsewhere, the focus will be lost and the background color will disappear.

This article mainly introduces the selection, highlighting, and positioning functions of the el-tree of vue2+elementUI. The positioning function involves no matter which menu is currently in. After deleting a certain menu, the refresh menu will jump to all the history that needs to be preserved. Expand Status , this article introduces you in detail through example codes, which has certain reference value for your study or work. Friends who need it can refer to it. The desired
effect is as follows:

 The mouse slides over the highlighted text and background color, and the mouse clicks elsewhere, the background color and text remain in place


Implementation

html partly implemented

<el-tree
                ref="tree"
                :data="treeData"
                :current-node-key="currentNodeKey"
                node-key="id"
                :default-expanded-keys="defaultExpandedKeys"
                @node-click="handleNodeClick"
                @node-expand="handleNodeExpand"
                @node-collapse="handleNodeCollapse"
                :highlight-current="true"
                :expand-on-click-node="false"
                :props="defaultProps"
                v-loading="treeLoading"
        >

js partial implementation

 export default {
    data() {
      return {
        defaultProps: {
          children: "children",
          label: "name",
        },
        currentNodeKey: 1, // 当前选中节点
        treeLoading: false, // treeLoading
        defaultExpandedKeys: ['1'],
        treeData: [{
          id: 1,
          name: '全部',
          level: 1,
          children: [{
            id: 2,
            level: 2,
            name: '未分类',
          },
            {
              id: 4,
              name: '二级 1-1',
              level: 2,
              children: [{
                id: 9,
                level: 3,
                name: '三级 1-1-1'
              }, {
                id: 10,
                level: 3,
                name: '三级 1-1-2'
              }]
            }]
        }]
      };
    },
    methods: {
     /**
       * @description:  点击节点
       * @param {Object} data
       * @param {Object} node
       * @return {*}
       */
      handleNodeClick(data, node){
        this.currentNodeKey = data.id;
        // 判断点击的层级进行操作
        if(node.level === 1){
          console.log('第一层data1',data);
          console.log('第一层node1',node);
        }else if(node.level === 2){
          console.log('第二层data2',data);
          console.log('第二层node2',node);
        }else if(node.level === 3){
          console.log('第三层data3',data);
          console.log('第三层node3',node);
        }
      },
      /**
       * @description:  树节点展开
       * @param {Object} data
       * @return {*}
       */
      handleNodeExpand (data) {
        // 判断当前节点是否存在, 存在不做处理,不存在则存到数组里
        if (!this.defaultExpandedKeys.includes(data.id)) {
          this.defaultExpandedKeys.push(data.id)
        }
      },
      /**
       * @description:  树节点关闭
       * @param {Object} data
       * @return {*}
       */
      handleNodeCollapse (data) {
        for (let i = 0; i < this.defaultExpandedKeys.length; i++) {
          if (this.defaultExpandedKeys[i] === data.id) {
            this.defaultExpandedKeys.splice(i, 1);
          }
        }
      },
/**
       * @description: 获取树形结构菜单
       * @param {*}
       * @return {*}
       */
      async getTreeData(){
        this.treeLoading = true;
        await request({
          url: ``,
          method: 'get',
        }).then(res => {
          this.treeData = res.data;
          // 不加会跳到全部
          this.$nextTick(() => {
            this.$refs['tree'].setCurrentKey(this.currentNodeKey);
          })
        }).finally(() => {
          this.treeLoading = false;
        });
      },
/**
       * @description: 文件夹删除
       * @param {String} id
       */
      delFileConfirm(id) {
        const h = this.$createElement;
        this.$msgbox({
          title: '提示',
          message: h('p', null, [h('span', null, `确认删除该文件夹及其子文件夹吗?`)]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              request({
                url: '',
                method: 'post',
                data: {
                  id,
                },
              }).then(async (res) => {
                if (res.code === '0') {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                  done();
                  await this.getTreeData();
                }
              }).finally(()=> {
                instance.confirmButtonLoading = false;
              })
            } else {
              done();
              instance.confirmButtonLoading = false;
            }
          }
        }).then(action => {});

      },
    }
  };
</script>

css partial implementation 

Mainly for highlighting

<style scoped>
/*  鼠标hover改变背景颜色 */
  .el-tree /deep/ .el-tree-node  .el-tree-node__content:hover {
    background-color: #f0f7ff !important;
    color: #409eff;
  }
  /*  颜色高亮 */
  /deep/ .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    color: #409eff;
  }
</style>

parameter indication

:default-expand-all ----> open all nodes by default

:default-expanded-keys----> default opened nodes

:data="treeData" ----> Mandatory display data

@node-click="handleNodeClick" ----> callback when the node is clicked

node-key="id" ----> Set the key of the selected data

 :current-node-key="currentNodeKey" ----> Set the initially selected value

:highlight-current="true" ----> set highlight must write

:props="defaultProps" ----> can configure the attribute value of the node label

key point

  1. Set highlight-current to true
  2. Set current-node-key to currentNodeKey, and reset currentNodeKey when refreshing the interface at the same time, the code is as follows
    this.$nextTick(() => {
      this.$refs['tree'].setCurrentKey(this.currentNodeKey);
    })
  3. If it is not expanded by default, it needs to be refreshed to keep the original expanded data and continue to expand
    @node-expand="handleNodeExpand" // 展开节点时触发的函数
    @node-collapse="handleNodeCollapse" // 关闭节点时触发的函数


Guess you like

Origin blog.csdn.net/qq_37485170/article/details/131188327