element-ui el-tree自定义选中背景色

1,004 阅读1分钟
  • 之前遇到过el-tree根据数据自定义背景色 但组件没有提供 自已修改要使用原生js修改dom 有些麻烦

  • 看到这篇文章提供了思路 juejin.cn/post/714323…

  • 整理如下 做备忘用 vue3的element-plus已经提供了组件方法已经不需要

  • 代码如下

<template>
  <el-tree
    :data="data"
    show-checkbox
    node-key="id"
    :default-expanded-keys="[2, 3]"
    :default-checked-keys="[5]"
    :props="defaultProps"
  >
    <span class="custom-tree-node" :style="{'--width':node.level-1}" :class="{'is-active':node.checked}" slot-scope="{ node, data }">
      <span>{{ data.label }}{{getValue(node)}}</span>
      <div class="multiBackChange"></div>
    </span>
  </el-tree>
</template>

<script>
export default {
  data() {
    return {
      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",
      },
    };
  },
  methods:{
    getValue(val){
      console.log(val)
    },
  },
};
</script>

<style>
.el-tree-node{
  /* position: relative; */
}

.el-tree-node__content{
  /* position: absolute; */
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  /* background: red; */
  position: relative;
}

.custom-tree-node.is-active{
  background: red;
}

.custom-tree-node.is-active .multiBackChange{
  width: calc(14px + 24px + calc(18px * var(--width)) + 4px);
  height: 100%;
  background: red;
  position: absolute;
  transform: translateX(-100%);
  left: 0;
  top: 0;
}
.multiBackChange {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.multiBackChange.is-active{
  background: rgba(0,0,0,.4);
  /* z-index: -1; */
}

.el-tree-node__expand-icon{
  position: relative;
  z-index: 9;
}

/* .el-tree-node:focus > .el-tree-node__content {
    background: rgba(0,0,0,0);
}
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: rgba(0,0,0,0);
} */
</style>