关于vue.js:饿了么UI中eltree中的树节点选中高亮的两种常用方式highlightcurrent属性

11次阅读

共计 1854 个字符,预计需要花费 5 分钟才能阅读完成。

问题形容

咱们晓得树节点经常须要抉择,为了看得更加直观显著,所以咱们须要设置选中的时候,让选中的那个树节点色彩高亮,本文记录一下罕用的三种形式,咱们先看一下效果图

效果图

形式一

第一步:

el-tree 组件标签上增加高亮属性 highlight-current,示意要开启高亮性能。

第二步:

而后在 css 中深度作用域高亮款式代码即可

<style lang="less" scoped>
    /deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      // 设置色彩
      background-color: #baf !important;
    }
</style>

留神这种形式是选中树节点高亮,即:树节点获取焦点是高亮,如果树节点失去焦点,也就是说点击了别的中央仍然是高亮状态,即还保留高亮状态

形式二

如果是想要那种,选中高亮,不选中就不高亮的成果,咱们独自应用 css 设置即可,这个时候就不必在树组件上加上 highlight-current 属性了,间接一句话获取焦点确定即可,如下语句:

<style lang="less" scoped>
    /deep/ .el-tree-node:focus > .el-tree-node__content {background-color: #bfa !important;}
</style>

上述两种形式都是通过 css 形式去管制的,咱们也能够通过 js 形式去管制的,比方默认第一项高亮

指定默认高亮树节点

应用 el-tree 组件的 setCurrentKey 办法,依据树组件的树节点的惟一 id 来制订某个树节点高亮。当然要搭配 node-key="id" 给树节点绑定惟一标识 id,同时也要开启高亮模式(加上 highlight-current 属性),而后形式一设置高亮的色彩款式要加上。初始化加载默认高亮,所以在 mounted 钩子中书写代码即可。

残缺代码

<template>
  <div class="box">
    <el-tree
      ref="myTree"
      node-key="id"
      :data="data"
      :props="defaultProps"
      highlight-current
    >
    </el-tree>
  </div>
</template>

<script>
export default {data() {
    return {
      data: [
        {
          name: "西游记",
          id: "xiyouji",
          children: [
            {
              name: "孙悟空",
              id: "sunwukong",
              children: [
                {
                  name: "大猴子",
                  id: "dahouzi",
                  children: [],},
                {
                  name: "二猴子",
                  id: "erhouzi",
                  children: [],},
              ],
            },
            {
              name: "猪八戒",
              id: "zhubajie",
              children: [],},
            {
              name: "沙和尚",
              id: "shaheshang",
              children: [],},
          ],
        },
        {
          name: "水浒传",
          id: "shuihuzhuan",
          children: [
            {
              name: "宋江",
              id: "songjiang",
              children: [],},
            {
              name: "武松",
              id: "wusong",
              children: [],},
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  mounted() {this.$nextTick(function () {this.$nextTick(() => {
        // myTree 数组件的 ref  默认让第一项高亮 
        // data 是树组件对应的数据
        // 通过 data 中的第一项的 id 找到对应的节点,而后把这个节点设置为高亮
        this.$refs.myTree.setCurrentKey(this.data[0].id);
      });
    });
  },
};
</script>
<style lang="less" scoped>
// 设置高亮色彩
/deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {background-color: #baf !important;}
</style>

setCurrentKey 办法是通过 key 设置某个节点的以后选中状态,应用此办法必须设置 node-key 属性,因为要确定唯一性,node-key=”id” 因为个别都是 id 具备唯一性,所以绑定 id。

正文完
 0