vue el-cascader组件change失效以及下拉框不消失的问题

1.前言

最近项目上用到el-cascader这个组件,需要可以选第一级菜单,也需要可以选第二级菜单,点击完成之后需要关闭下拉框。其实功能比较简单,找了很多资料,没有找到合适的方案,下面还是自己想了个方案才解决问题

2. 碰到的问题

1.如何让下拉框消失?
2.change方法只是值发生改变才会触发,如果是同一个值就不会触发这个方法,我看有些人还去改源码?

3. 如何解决这两个问题

首先需要change方法

    //关闭联级面板
    cascaderChange() {
   
      //监听值发生变化就关闭它
      this.$refs.cascaderLocation.dropDownVisible = false;
      this.$refs.cascaderType.dropDownVisible = false;
    },

然后还需要visible-change这个方法,当下拉框出现值为true,下拉框消失值为false

//地点
<el-cascader
  v-model="formSearch.location"
  :show-all-levels="false"
  :options="locations"
  :props="{ checkStrictly: true, expandTrigger: 'hover' }"
  ref="cascaderLocation"
  @change="cascaderChange"
  clearable
  style="width:210px;"
  @visible-change="value => cascaderVisibleChange(value, 'location')"
></el-cascader>

//算法类型
<el-cascader
  v-model="formSearch.type"
  :show-all-levels="false"
  :options="algorithms"
  :props="{ checkStrictly: true, expandTrigger: 'hover' }"
  style="width:130px;"
  ref="cascaderType"
  @change="cascaderChange"
  @visible-change="value => cascaderVisibleChange(value, 'type')"
></el-cascader>

项目里面用了两种类型的,逻辑是当点开下拉框,先把原始值保存起来,再把值直接赋值为空,保存起来的目的是防止用户没选直接关闭了下拉框,这种情况就需要用到原来保存起来的值

cascaderVisibleChange(value, type) {
   
  if (value) {
   
    if (type == "location") {
   
      this.oldLocation = this.formSearch.location;
      this.formSearch.location = "";
    } else if (type == "type") {
   
      this.oldType = this.formSearch.type;
      this.formSearch.type = "";
    }
  } else {
   
    if (type == "location" && !this.formSearch.location) {
   
      this.formSearch.location = this.oldLocation;
    } else if (type == "type" && !this.formSearch.type) {
   
      this.formSearch.type = this.oldType;
    }
  }
}

结果如下图:
在这里插入图片描述

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-16 10:30:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-16 10:30:04       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-16 10:30:04       82 阅读
  4. Python语言-面向对象

    2023-12-16 10:30:04       91 阅读

热门阅读

  1. Python 内置界面开发框架 Tkinter 入门指南

    2023-12-16 10:30:04       66 阅读
  2. Redisson分布式锁的实现原理(小白话)

    2023-12-16 10:30:04       58 阅读
  3. Vue组件的生命周期

    2023-12-16 10:30:04       57 阅读
  4. Ubuntu下COLMAP的编译与安装全攻略

    2023-12-16 10:30:04       64 阅读
  5. C语言实现动态数组

    2023-12-16 10:30:04       60 阅读
  6. 力扣221. 最大正方形

    2023-12-16 10:30:04       57 阅读
  7. 使用OpenCV和PIL库读取图片的区别

    2023-12-16 10:30:04       57 阅读