详解element-ui 组件el-autocomplete使用踩坑记录

 更新时间:2022年03月08日 09:43:47   作者:石耳  
最近使用了el-autocomplete组件,本文主要介绍了element-ui 组件el-autocomplete使用踩坑记录,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

项目遇到一个比较麻烦的需求,保存用户填写的历史记录,项目使用的element-ui,自然就使用了el-autocomplete组件,然后就是各种踩坑,以下记录以下写代码过程中遇到的问题

createFilter(queryString, filed) {
      console.log("createFilter==" + queryString)
      return (item) => {
        switch (filed) {
          case 'cardNum':
            break
          case 'cardPass': case 'userPhone': case 'userName': case 'userCardId':
            return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
            break
          case 'mobile':
            return (item.phone.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
            break
          default:
            break
        }
      };
    },

1、下拉框高度修改:

el-autocomplete组件样式默认有一个最大高度,超出高度会滚动,如图显示的大概有7、8条的数据,需求要求展示10条所以只能修改组件样式。

如图可以看到有一个max-height属性,修改这个样式就可了,但是写了样式代码不起作用,组件修改了:popper-append-to-body="false"之后样式起作用了,原理不太清楚,哪位大神知道原因的麻烦告诉我一下,多谢

<style scoped lang="less">

  /deep/ .inline-input {
    /deep/ .el-scrollbar__wrap {
      max-height: 360px; /*no*/
    }
  }
</style>

2、一个页面有多个el-autocomplete组件,所以我需要传入使用这个组件的字段名,然后修改fetch-suggestions方法为

:fetch-suggestions="((queryString, cb)=>{queryFun(queryString, cb,'userName')})用闭包的方式多传入一个字段的入参

<el-form-item label="使用人姓名:" prop="userName" :rules="[{ required: true, message: '请填写信息!',trigger: ['blur', 'change'] },
    { pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,20}$/, message: '请填写正确信息!',trigger: ['blur', 'change'] }]">
    <!-- <el-input @input="filterInput($event,'userName')" v-model="form.userName" autocomplete="off" maxlength="20"></el-input> -->
    <el-autocomplete @blur.stop="saveLocal($event.target.value,'userName')"     @input="filterInput($event,'userName')" class="inline-input" v-model="form.userName"     :fetch-suggestions="((queryString, cb)=>{queryFun(queryString, cb,'userName')})"     placeholder="请输入姓名" @select="((item)=>{handleSelect(item,'userName')})" :debounce=0 :popper-append-to-body="false">
  </el-autocomplete>
 </el-form-item>

3、需要保存的数据是校验通过后的数据,也就是输入完成blur之后再操作保存的逻辑,但是el-autocomplete组件blur事件不起作用,后查询资料说是因为click事件的优先级高于blur事件,所以要解决这个问题就解决事件冒泡问题,只需要使用vue的事件修饰符.stop就可以了,؏؏☝ᖗ乛◡乛ᖘ☝؏؏

@blur.stop="saveLocal($event.target.value,'userName')"

queryFun(queryString, cb, filed) {
      console.log(filed)
      let items = [];
      switch (filed) {
        case 'cardNum':
          break
        case 'cardPass':
          items = JSON.parse(localStorage.getItem("passHistory")) ? JSON.parse(localStorage.getItem("passHistory")) : [];
          break
        case 'userPhone':
          items = JSON.parse(localStorage.getItem("phoneHistory")) ? JSON.parse(localStorage.getItem("phoneHistory")) : [];
          break
        case 'userName':
          items = JSON.parse(localStorage.getItem("userNameHistory")) ? JSON.parse(localStorage.getItem("userNameHistory")) : [];
          break
        case 'mobile':
          break
        case 'userCardId':
          items = JSON.parse(localStorage.getItem("userCardIdHistory")) ? JSON.parse(localStorage.getItem("userCardIdHistory")) : [];
          break
        default:
          break
      }

      let results = queryString ? items.filter(this.createFilter(queryString, filed)) : items;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    }
createFilter(queryString, filed) {
      console.log("createFilter==" + queryString)
      return (item) => {
        switch (filed) {
          case 'cardNum':
            break
          case 'cardPass': case 'userPhone': case 'userName': case 'userCardId':
            return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
            break
          default:
            break
        }
      };
    },

4、第一次点击的时候会显示“请填写信息!”报错信息,再次点击选项就正常了,这个问题也是纠结了一阵儿,后来想起我的校验规则trigger 写的是‘blur’,下拉框应该触发change事件,修改为

trigger: ['blur', 'change'],解决

handleSelect(item, filed) {
      console.log(item);
      console.log("handleSelect==" + filed);
      let _this = this;
      switch (filed) {
        case 'cardNum':
          break
        case 'cardPass': case 'userPhone': case 'userName':
          _this.$set(_this.form, filed, item.value);
          break
        case 'userCardId':
          this.form.userCardId = item.userCardId;
          this.getAge(item.userCardId);
          break
        default:
          break
      }
    },

5、姓名禁止输入数字等使用input事件,将不符合正则的内容替换成空,代码如下

filterInput(e, filed) {
      console.log("filterInput=====")
      console.log(e)
      switch (filed) {
        case 'cardNum':
          this.form[filed] = e.replace(/[^\a-\z\A-\Z0-9]/g, '');
          this.form[filed] = this.form[filed].slice(0, 12);
          break
        case 'cardPass':
          this.form[filed] = e.replace(/[^\a-\z\A-\Z0-9]/g, '');
          this.form[filed] = this.form[filed].slice(0, 6);
          break
        case 'userPhone':
          this.form[filed] = e.replace(/[^0-9]/g, '');
          this.form[filed] = this.form[filed].slice(0, 11);
          break
        case 'userName':
          this.form[filed] = e.replace(/[^\a-\z\A-\Z\u4e00-\u9fa5]/g, '');
          this.form[filed] = this.form[filed].slice(0, 20);
          break
        case 'mobile':
          this.form[filed] = e.replace(/[^0-9]/g, '');
          this.form[filed] = this.form[filed].slice(0, 11);
          break
        case 'userCardId':
          this.form[filed] = e.replace(/[^0-9Xx]/g, '');
          this.form[filed] = this.form[filed].slice(0, 18);
          break
        default:
          this.form[filed] = e.replace(/[\u4e00-\u9fa5]/g, '');
          break
      }
      // this.saveLocal(this.form[filed], filed)
      this.$forceUpdate();
    },

6、校验通过后存储到localStorage,总觉得代码有点重复,不过改bug比较着急,大神有更好的写法,欢迎评论区留言

// 保存验证通过的信息
    saveLocal(val, filed) {
      var reg = "";
      switch (filed) {
        case 'cardNum':
          reg = /[0-9a-zA-Z]{12}/;
          if (reg.test(val)) {

            // 存储正确卡号到历史信息
            this.cardHistory.unshift({ "cardNum": val });
            // 历史消息去重
            var hash = {};
            this.cardHistory = this.cardHistory.reduce(function (item, next) {
              hash[next.cardNum] ? '' : hash[next.cardNum] = true && item.push(next);
              return item
            }, []);
            if (this.cardHistory.length > 10) {
              this.cardHistory.pop();
            }
            localStorage.setItem("cardList", JSON.stringify(this.cardHistory));
          }
          break
        case 'cardPass':
          reg = /[0-9a-zA-Z]{6}/;
          if (reg.test(val)) {
            // 存储正确卡号到历史信息
            this.passHistory.unshift({ "value": val });
            // 历史消息去重
            var hash = {};
            this.passHistory = this.passHistory.reduce(function (item, next) {
              hash[next.value] ? '' : hash[next.value] = true && item.push(next);
              return item
            }, []);
            if (this.passHistory.length > 10) {
              this.passHistory.pop();
            }
            localStorage.setItem("passHistory", JSON.stringify(this.passHistory));
          }
          break
        case 'userPhone':
          reg = /^1[3-9]\d{9}$/;
          if (reg.test(val)) {
            // 存储正确卡号到历史信息
            this.phoneHistory.unshift({ "value": val });
            // 历史消息去重
            var hash = {};
            this.phoneHistory = this.phoneHistory.reduce(function (item, next) {
              hash[next.value] ? '' : hash[next.value] = true && item.push(next);
              return item
            }, []);
            if (this.phoneHistory.length > 10) {
              this.phoneHistory.pop();
            }
            localStorage.setItem("phoneHistory", JSON.stringify(this.phoneHistory));
          }
          break
        case 'userName':
          reg = /^[a-zA-Z\u4e00-\u9fa5]{2,20}$/;
          if (reg.test(val)) {
            // 存储正确卡号到历史信息
            this.userNameHistory.unshift({ "value": val });
            // 历史消息去重
            var hash = {};
            this.userNameHistory = this.userNameHistory.reduce(function (item, next) {
              hash[next.value] ? '' : hash[next.value] = true && item.push(next);
              return item
            }, []);
            if (this.userNameHistory.length > 10) {
              this.userNameHistory.pop();
            }
            localStorage.setItem("userNameHistory", JSON.stringify(this.userNameHistory));
          }
          break
        case 'mobile':
          break
        case 'userCardId':
          reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
          if (reg.test(val)) {
            // 存储正确卡号到历史信息
            this.userCardIdHistory.unshift({ "value": val });
            // 历史消息去重
            var hash = {};
            this.userCardIdHistory = this.userCardIdHistory.reduce(function (item, next) {
              hash[next.value] ? '' : hash[next.value] = true && item.push(next);
              return item
            }, []);
            if (this.userCardIdHistory.length > 10) {
              this.userCardIdHistory.pop();
            }
            localStorage.setItem("userCardIdHistory", JSON.stringify(this.userCardIdHistory));
          }
          break
        default:
          break
      }
    },

到此这篇关于详解element-ui 组件el-autocomplete使用踩坑记录的文章就介绍到这了,更多相关element组件el-autocomplete使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vue插槽的作用

    Vue插槽的作用

    插槽(slot)是 vue 为组件的封装者提供的能力。允许开发者在封装组件时,把不确定的、希望由用户指定的部分定义为插槽。可以把插槽认为是组件封装期间,为用户预留的内容的占位符
    2022-09-09
  • vue计算属性computed方法内传参方式

    vue计算属性computed方法内传参方式

    这篇文章主要介绍了vue计算属性computed方法内传参方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • Vue如何调用接口请求头增加参数

    Vue如何调用接口请求头增加参数

    这篇文章主要介绍了Vue如何调用接口请求头增加参数,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • 关于在vscode使用webpack指令显示

    关于在vscode使用webpack指令显示"因为在此系统中禁止运行脚本"问题(完美解决)

    这篇文章主要介绍了解决在vscode使用webpack指令显示"因为在此系统中禁止运行脚本"问题,本文给大家分享完美解决方法,需要的朋友可以参考下
    2021-07-07
  • vue.js实现条件渲染的实例代码

    vue.js实现条件渲染的实例代码

    这篇文章主要介绍了vue.js实现条件渲染的实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • vue.js 实现点击按钮动态添加li的方法

    vue.js 实现点击按钮动态添加li的方法

    今天小编就为大家分享一篇vue.js 实现点击按钮动态添加li的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-09-09
  • 基于Vue-cli快速搭建项目的完整步骤

    基于Vue-cli快速搭建项目的完整步骤

    这篇文章主要给大家介绍了关于如何基于Vue-cli快速搭建项目的完整步骤,文中通过示例代码以及图片将搭建的步骤一步步介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • VUE父组件异步获取数据,子组件接收的值为空的问题

    VUE父组件异步获取数据,子组件接收的值为空的问题

    这篇文章主要介绍了VUE父组件异步获取数据,子组件接收的值为空的问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • vue-cli脚手架搭建方式(vue脚手架方式搭建)

    vue-cli脚手架搭建方式(vue脚手架方式搭建)

    这篇文章主要介绍了vue-cli(vue脚手架方式搭建),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • vue3+springboot部署到Windows服务器的详细步骤

    vue3+springboot部署到Windows服务器的详细步骤

    这篇文章主要介绍了vue3+springboot部署到Windows服务器,配置Nginx时,因为现在是把vue前端交给了Nginx代理,所以这里的端口号不一定是我们在vue项目中设置的端口号,本文给大家介绍的非常详细,需要的朋友参考下吧
    2022-10-10

最新评论