返回

Vue 下拉框 (多选) 嵌套异步树的完整指南

前端

揭秘 Vue 下拉框 (多选) 嵌套异步树的实现奥秘

前言

在构建 Vue 项目时,我们经常需要在下拉框中展示嵌套数据结构。当数据庞大且需要异步加载时,使用普通的 el-select 组件可能无法满足我们的需求。本文将深入探讨如何使用异步树嵌套 el-select 多选下拉框,并提供一个真实可靠的解决方案。

技术实现

1. 自定义树结构

不同于常规的 el-select,el-select 多选下拉框需要将 el-option 选项放入树结构中。但是,仅使用 slot 无法实现这一目标。

2. 异步加载树结构

为了高效处理海量数据,我们将采用异步加载树结构的方法。这与饿了么官方网站的实现类似。

3. 自定义组件

为了封装复杂逻辑,我们将创建一个自定义组件,该组件将负责处理树结构的异步加载和渲染。

实现步骤

1. 创建自定义树结构组件

<template>
  <el-cascader
    v-model="selectedKeys"
    :options="options"
    :props="props"
    :filterable="filterable"
    collapse-tags
    multiple
  />
</template>

<script>
import { ref } from 'vue'
import { fetchTreeData } from '@/api'

export default {
  props: {
    props: Object,
    filterable: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:selectedKeys'],
  setup(props, { emit }) {
    const options = ref([])
    const selectedKeys = ref([])

    const fetchOptions = async () => {
      const res = await fetchTreeData()
      options.value = res.data
    }

    fetchOptions()

    const watchKeys = watch(() => selectedKeys.value, (val) => {
      emit('update:selectedKeys', val)
    })

    onBeforeUnmount(() => {
      watchKeys()
    })

    return {
      options,
      selectedKeys
    }
  }
}
</script>

2. 使用自定义组件

<template>
  <custom-tree
    :props="{ value: 'value', label: 'label' }"
    @update:selectedKeys="handleSelectedKeys"
  />
</template>

<script>
import CustomTree from '@/components/CustomTree'

export default {
  components: { CustomTree },
  methods: {
    handleSelectedKeys(keys) {
      console.log(keys)
    }
  }
}
</script>

SEO 优化

结论

通过使用异步树嵌套 Vue 下拉框 (多选) 组件,我们能够有效地展示复杂的数据结构并满足用户在海量数据中的交互需求。本文提供的解决方案既全面又易于实施,可帮助您构建出强大的、可扩展的用户界面。