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
        }
      };
    },

 

項目遇到一個比較麻煩的需求,保存用戶填寫的歷史記錄,項目使用的element-ui,自然就使用了el-autocomplete組件,然后就是各種踩坑,以下記錄以下寫代碼過程中遇到的問題

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
      }
    },

記錄一下折騰一天的工作成果,嗯~下班


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM