关于前端:Vue实现无限级树形选择器无第三方依赖

6次阅读

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

想要在 Vue 中实现一个这样的有限级树形选择器其实并不难,关键点在于利用 递归组件 高阶事件监听,上面咱们就一步步来实现它。

简略实现下款式

创立 Tree.vue 组件(为不便浏览,代码有省略):

<template>
  <ul class="treeMenu">
    <li v-for="(item, index) in data" :key="index">
      <i v-show="item.children" :class="triangle" />
      <p :class="treeNode">
        <label class="checkbox-wrap" @click="checked(item)">
          <input v-if="isSelect" v-model="item.checked" type="checkbox" class="checkbox" />
        </label>
        <span class="title" @click="tap(item, index)">{{item.title}}</span>
      </p>
      <!-- TODO -->
    </li>
  </ul>
</template>
<script>
export default {
  name: 'TreeMenus',
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    // 是否开启节点可抉择
    isSelect: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {,
      tapScopes: {},
      scopes: {},}
  },
}
</script>
<style scoped>
...... some code ......
</style>

开展膨胀咱们应用 CSS 来创立一个三角形:

.triangle {
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-left: 8px solid grey;
  transition: all 0.1s;
  left: 6px;
  margin: 6px 0 0 0;
}

而后定义一个开展时的 class,旋转角度调整一下定位:

.caret-down {transform: rotate(90deg);
  left: 2px;
  margin: 9px 0 0 0;
}

因为每个节点管制开展闭合的变量都是独立的,为了不净化数据,这里咱们定义一个对象 tapScopes 来管制就好,记得应用 $set 来让视图响应变动:

// 当点击三角形时,图标变动:changeStatus(index) {this.$set(this.tapScopes, index, this.tapScopes[index] ? (this.tapScopes[index] === 'open' ? 'close' : 'open') : 'open')
}

递归渲染

当初咱们只渲染了第一层数据,如何循环渲染下一级数据呢,其实很简略,往上面 TODO 的地位插入组件本身即可(相当于引入了本身作为 components),只有组件设置了 name 属性,Vue 就能够调用该组件,:

<li v-for="(item, index) in data">
// .... some code ....
    <tree-menus :data="item.children" v-bind="$props" />
</li>

<script>
export default {
  name: 'TreeMenus'
// .... some code ....

递归组件接管雷同的 props 咱们不用一个个传递,能够间接写成 v-bind="$props" 把代理的 props 对象传进去(比方下面定义的 isSelect 就会被始终传递),只不过 data 被咱们覆写成了循环的下一级。最初应用 v-show 管制一下开展闭合的成果,根本的交互就实现进去了:

<img src=”https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/120f844c020248d6bf872526f1818deb~tplv-k3u1fbpfcp-watermark.image?” width=”50%” />

<img src=”https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a74182e812a44918a1d1dcc07b8e08e5~tplv-k3u1fbpfcp-watermark.image?” width=”50%” />

定义参数

树形构造数据个别都是如下的 嵌套构造 ,再简单也只不过是字段变多了而已,这几个 特色字段 是必定存在的:keylabelchildren,以上面的参考数据为例: 这里的 keyid,用于标识唯一性(该字段在整棵树中是惟一的),label 则是 title 字段,用于显示节点名称,最初的 children 则是指下一级节点,它的特色与父级统一。

[
    {
        id: 1,
        title: "",
        children: [{
            id: 2,
            title: "",
            children: ......
        }]
    }
]

所以咱们的选择器组件能够定义一个 要害参数选项,用于指定节点中的这几个属性值。

props: {
// ... some code ....
    props: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          label: 'title',
          key: 'id',
        }
      },
    },
  },

组件中的一些要害参数都批改成动静的模式:

:key="index"            =>       :key="item[props.key]"
:data="item.children"   =>       :data="item[props.children]"
{{item.title}}        =>       {{item[props.label] }}

实现点击事件

当初咱们来实现一个点击事件 node-click: 为节点绑定一个 click 事件,点击后触发 $emit 把节点对象传进办法中即可:

<span class="title" @click="tap(item, index)"> ... </span>

methods: {tap(item, index) {this.$emit('node-click', item)
    }
.........

// 调用时:

<Tree @node-click="handle" :data="treeData" />

methods: {handle(node) {console.log('点击节点 Data :', node)
    }
.......

这时问题来了,因为组件是递归 嵌套 的,如何在子节点中点击时也能触发最外层的事件呢?这时就须要利用 Vue 提供的 $listeners 这个 property,配合 v-on="$listeners" 将所有的事件监听器指向组件中循环的子组件:

<tree-menus .... v-on="$listeners"></tree-menus>

<img src=”https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7a7b6c257a024ba4852b51f56fe47012~tplv-k3u1fbpfcp-watermark.image?” width=”70%” />

往组件中定义任何其它办法,都能够像这样失常触发到调用它的组件那里。

残缺代码

Tree.vue

<template>
  <ul class="treeMenu">
    <li v-for="(item, index) in data" :key="item[props.key]">
      <i v-show="item[props.children]" :class="['triangle', carets[tapScopes[index]]]" @click="changeStatus(index)" />
      <p :class="['treeNode', {'treeNode--select': item.onSelect}]">
        <label class="checkbox-wrap" @click="checked(item)">
          <input v-if="isSelect" v-model="item.checked" type="checkbox" class="checkbox" />
        </label>
        <span class="title" @click="tap(item, index)">{{item[props.label] }}</span>
      </p>
      <tree-menus v-show="scopes[index]" :data="item[props.children]" v-bind="$props" v-on="$listeners"></tree-menus>
    </li>
  </ul>
</template>
<script>
const CARETS = {open: 'caret-down', close: 'caret-right'}
export default {
  name: 'TreeMenus',
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    isSelect: {
      type: Boolean,
      default: false,
    },
    props: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          label: 'title',
          key: 'id',
        }
      },
    },
  },
  data() {
    return {
      carets: CARETS,
      tapScopes: {},
      scopes: {},}
  },
  methods: {operation(type, treeNode) {this.$emit('operation', { type, treeNode})
    },
    tap(item, index) {this.$emit('node-click', item)
    },
    changeStatus(index) {this.$emit('change', this.data[index])
      // 图标变动
      this.$set(this.tapScopes, index, this.tapScopes[index] ? (this.tapScopes[index] === 'open' ? 'close' : 'open') : 'open')
      // 开展闭合
      this.$set(this.scopes, index, this.scopes[index] ? false : true)
    },
    async checked(item) {this.$emit('checked', item)
    },
  },
}
</script>
<style scoped>
.treeMenu {
  padding-left: 20px;
  list-style: none;
  position: relative;
  user-select: none;
}

.triangle {
  transition: all 0.1s;
  left: 6px;
  margin: 6px 0 0 0;
  position: absolute;
  cursor: pointer;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-left: 8px solid grey;
}
.caret-down {transform: rotate(90deg);
  left: 2px;
  margin: 9px 0 0 0;
}
.checkbox-wrap {
  display: flex;
  align-items: center;
}
.checkbox {margin-right: 0.5rem;}
.treeNode:hover,
.treeNode:hover > .operation {
  color: #3771e5;
  background: #f0f7ff;
}
.treeNode--select {background: #f0f7ff;}
.treeNode:hover > .operation {opacity: 1;}
p {
  position: relative;
  display: flex;
  align-items: center;
}
p > .title {cursor: pointer;}
a {color: cornflowerblue;}
.operation {
  position: absolute;
  right: 0;
  font-size: 18px;
  opacity: 0;
}
</style>

Mock.js

export default {
  stat: 1,
  msg: 'ok',
  data: {
    list: [
      {
        key: 1,
        title: '一级机构部门',
        children: [
          {
            key: 90001,
            title: '测试机构 111',
            children: [
              {
                key: 90019,
                title: '测试机构 111-2',
              },
              {
                key: 90025,
                title: '机构机构',
                children: [
                  {
                    key: 90026,
                    title: '机构机构 -2',
                  },
                ],
              },
            ],
          },
          {
            key: 90037,
            title: '另一个机构部门',
          },
        ],
      },
      {
        key: 2,
        title: '小卖部总舵',
        children: [
          {
            key: 90037,
            title: '小卖部河边分部',
          },
        ],
      },
    ],
  },
}

调用组件

<template>
  <div class="about">
    <Tree :isSelect="isSelect" :data="treeData" @node-click="handle" @change="loadData" />
  </div>
</template>

<script>
import Tree from '@/Tree.vue'
import json from '@/mock.js'

export default {components: { Tree},
  data() {
    return {treeData: [],
      isSelect: false,
      defaultProps: {
        children: 'children',
        label: 'title',
        key: 'id',
      },
    }
  },
  created() {this.treeData = json.data.list},
  methods: {handle(node) {console.log('点击节点 Data :', node)
    },
    loadData(treeNode) {console.log(treeNode)
      // eg: 动静更新子节点
      // treeNode.children = JSON.parse(JSON.stringify(json.data.list))
      // this.treeData = [...this.treeData]
    },
  },
}
</script>

以上就是文章的全部内容,心愿对你有所帮忙!如果感觉文章写的不错,能够点赞珍藏,也欢送关注,我会继续更新更多前端有用的常识与实用技巧,我是茶无味 de 一天,心愿与你独特成长~

正文完
 0