当前位置:首页 > VUE

vue实现级联

2026-03-27 10:33:15VUE

Vue 实现级联选择器的方法

级联选择器(Cascader)是常见的表单组件,用于处理多层级联动数据选择(如省市区选择)。以下是几种实现方式:

vue实现级联

使用 Element UI 的 Cascader 组件

Element UI 提供了成熟的级联选择器组件,适用于 Vue 2 项目:

vue实现级联

<template>
  <el-cascader
    v-model="selectedOptions"
    :options="options"
    @change="handleChange">
  </el-cascader>
</template>

<script>
export default {
  data() {
    return {
      selectedOptions: [],
      options: [{
        value: 'province1',
        label: '省份1',
        children: [{
          value: 'city1',
          label: '城市1'
        }]
      }]
    };
  },
  methods: {
    handleChange(value) {
      console.log(value);
    }
  }
};
</script>

使用 Ant Design Vue 的 Cascader

Ant Design Vue 的级联组件适用于 Vue 3 或 Vue 2:

<template>
  <a-cascader
    v-model:value="selectedOptions"
    :options="options"
    placeholder="请选择"
  />
</template>

<script>
import { ref } from 'vue';
export default {
  setup() {
    const selectedOptions = ref([]);
    const options = [
      {
        value: 'zhejiang',
        label: '浙江',
        children: [
          { value: 'hangzhou', label: '杭州' }
        ]
      }
    ];
    return { selectedOptions, options };
  }
};
</script>

手动实现级联逻辑

若需完全自定义,可通过动态加载子选项实现:

<template>
  <select v-model="selectedProvince" @change="loadCities">
    <option v-for="p in provinces" :value="p.id">{{ p.name }}</option>
  </select>
  <select v-model="selectedCity" :disabled="!selectedProvince">
    <option v-for="c in cities" :value="c.id">{{ c.name }}</option>
  </select>
</template>

<script>
export default {
  data() {
    return {
      selectedProvince: null,
      selectedCity: null,
      provinces: [{ id: 1, name: '省份1' }],
      cities: []
    };
  },
  methods: {
    loadCities() {
      this.cities = this.getCitiesByProvince(this.selectedProvince);
    }
  }
};
</script>

关键注意事项

  • 数据格式:级联数据通常为嵌套结构,需包含 valuelabelchildren 字段。
  • 异步加载:对于大数据量,可通过 lazy 属性和 load 方法实现按需加载。
  • 表单验证:结合 v-model 和验证库(如 VeeValidate)实现校验。

示例:异步加载实现

<el-cascader
  :props="{
    lazy: true,
    lazyLoad(node, resolve) {
      fetch(`/api/regions?parent=${node.value||0}`)
        .then(res => resolve(res.data))
    }
  }"
/>

通过上述方法,可灵活实现不同场景下的级联选择需求。

标签: 级联vue
分享给朋友:

相关文章

vue列表实现

vue列表实现

Vue 列表实现方法 使用 v-for 指令 v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items 或 (item, index)…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

tabbar 实现 vue

tabbar 实现 vue

在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue Router 结合自定义组件 创建一个自定义的 TabBar 组件,结合 Vue Router 实现…

vue实现groupbox

vue实现groupbox

Vue 实现 GroupBox 组件 在 Vue 中实现类似 GroupBox 的效果可以通过自定义组件完成。GroupBox 通常是一个带有标题的边框容器,用于将相关控件分组显示。 基本实现方法…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

轮播vue实现

轮播vue实现

使用 Vue 实现轮播功能 基础轮播实现 安装依赖(如使用 Swiper): npm install swiper vue-awesome-swiper 组件代码示例: <template&…