级联下拉限制条目

48 阅读1分钟

通过element-ui级联下拉组件为例

<template>
  <el-cascader
    v-model="selectedList"
    popper-class="location"
    placeholder="所在地区"
    filterable
    :props="{ multiple: true, expandTrigger: 'hover', checkStrictly: true }"
    :show-all-levels="false"
    :options="locationOptions"
    @change="handleLocationChange"
  >
</el-cascader>
</template>

<script>
export default {
  data() {
    return {
      maxNum: 12,
      selectedList: [], // 保存用户选择的地区信息
      locationOptions: [ // 包含所有可选的地区数据对象
        { value: 1002, label: "北京" },
        { value: 1024, label: "上海" },
        {
          value: 1001,
          label: "安徽",
          children: [
            { value: 100106, label: "合肥" },
            { value: 100114, label: "芜湖" },
            { value: 100101, label: "蚌埠" }
          ]
        },
        {
          value: 1003,
          label: "福建",
          children: [
            { value: 100300, label: "福州" },
            { value: 100307, label: "厦门" },
            { value: 100306, label: "三明" },
            { value: 100305, label: "泉州" },
            { value: 100301, label: "龙岩" }
          ]
        }
      ]
    }
  },

  watch: {
    // 所在地区,最多允许选择maxNum个
    selectedList: function (val, oldVal) {
      const { maxNum } = this
      if (val.length > maxNum) {
        this.$message.error(`最多可选${maxNum}个`)
        this.$nextTick(() => (this.selectedList = oldVal))
      }
    }
  }
}
</script>