自学内容网 自学内容网

element ui中的el-tree自定义每个节点,前面加不同颜色的块

<template>
  <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" :render-content="renderContent">
  </el-tree>
</template>

<script>
export default {
  data() {
    return {
      data: [
        {
          label: "一级 1",
          color: "yellow",
          children: [
            {
              label: "二级 1-1",
              color: "green",
              children: [
                {
                  label: "三级 1-1-1",
                  color: "red",
                },
              ],
            },
          ],
        },
        {
          label: "一级 2",
          color: "yellow",
          children: [
            {
              label: "二级 2-1",
              color: "green",
              children: [
                {
                  label: "三级 2-1-1",
                  color: "cyan",
                },
              ],
            },
            {
              label: "二级 2-2",
              color: "green",
              children: [
                {
                  label: "三级 2-2-1",
                  color: "red",
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  methods: {
    handleNodeClick(data) {
      console.log(data);
    },
    renderContent(h, { node, data, store }) {

      // 如果是子节点,添加色块
      if (!data.children && data.color) {
       
        return h("span", [
          h("span", {
            style: {
              display: "inline-block",
              width: "20px",
              height: "20px",
              backgroundColor: data.color, // 生成随机颜色或指定颜色
              marginRight: "8px",
              verticalAlign: "middle",
            },
          }),
          h("span", node.label),
        ]);
      } else {
        // 如果是父节点,不添加色块 
        // return h('span', node.label);
        return h("span", [
          h("span", {
            style: {
              display: "inline-block",
              width: "20px",
              height: "20px",
              backgroundColor: data.color, // 生成随机颜色或指定颜色
              marginRight: "8px",
              verticalAlign: "middle",
            },
          }),
          h("span", node.label),
        ]);
      }
    },
  },
};
</script>

<style></style>


原文地址:https://blog.csdn.net/weixin_46631078/article/details/140438877

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!