【每天學一點-06】在Vue中使用Vant-Picker選擇器,並且給選擇器添加一個類似Antd-Select-showSearch的搜索功能

一、在Vant文檔中,Picker組件的API中是沒有showSearch這一選項的

1、Vant-Picker 文檔

 

2、Antd-Select 文檔

 

 

3、需要完成的需求

 

 

 

 

 

4、因為在H5項目中出現了類似需求,也就是在Picker-title的位置加一個搜索框,picker列表數據根據搜索顯示

 

 

二、在Picker的title位置嵌入一個搜索框,使得Picker中顯示的數據是根據搜索框輸入內容查詢後篩選的數據。

1、基礎程式碼部分

<template>
  <van-picker
    title="標題"
    :columns="columns"     //數據列表
    @confirm="onConfirm"   //確認觸發
    @cancel="onCancel"     //取消觸發
    @change="onChange"     //選項改變觸發
  />
</template>
<script> import { Picker } from 'vant'  //引用組件
export default { name: 'demo', data() { return { columns: [],   //組件使用數據列表 } }, mounted() {   //初始化數據 this.getList();  //載入頁面獲取數據 }, methods: { /* 獲取數據列表方法 */ async getList() { try{ const { res } = await = getList(); //請求封裝介面 const { code, msg, data } = res;  //介面返回數據 if( code === 200){ this.columns = data;  //存入數據 } } catch( e ) { throw new Error( msg ) } } } } </script>
<style lang="less" scoped> </style>

  

 

2、進行改造

<template>
  <van-picker
    title="標題"
    :columns="searchColumns"     //數據列表
    @confirm="onConfirm"   //確認觸發
    @cancel="onCancel"     //取消觸發
    @change="onChange"     //選項改變觸發
  >
    <template #title>  //#title 顯示在picker-title位置
      <van-field
        v-model="searchKey"  //雙向綁定數據
        placeholder="請輸入搜索內容"
        clearable
      />
    </template>
  </van-picker>
</template>

<script>
import { picker, field } from 'vant'  //引用組件

export default {
  name: 'demo',
  data() {
    return {
      columns: [],   //組件使用數據列表,初始化後不改變
      searchColumns: [],  //搜索篩選後的數據列表,隨著查詢內容改變  
    }
  },
  mounted() {        //初始化數據
    this.getList();  //載入頁面獲取數據
  },
  methods: {
    /* 獲取數據列表方法 */
    async getList() {
      try{
        const { res } = await = getList(); //請求封裝介面
        const { code, msg, data } = res;  //介面返回數據
        if( code === 200){
          this.columns = data;  //存入數據
          this.searchColumns = data;  //給查詢數組初始化數據
        }
      } catch( e ) { throw new Error( msg ) }
    }
  },
  watch: {  //實時監聽搜索輸入內容
    searchKey: function () {
      let key = String( this.searchKey );
      key =  key.replace( /\s*/g, "" );  //去除搜索內容中的空格
      const reg new RegExp( key, "ig" ); //匹配規則-i:忽略大小寫,g:全局匹配
      this.searchColumns = this.columns.filter( item => item.name.match( reg ) !=null );  //進行篩選,將篩選後的數據放入新的數組中
    }
  }
}
</script>

<style lang="less" scoped>
</style>

  

 

三、實現思路

1、首先對搜索框進行數據的雙向綁定,然後使用Vue-watch進行數據監聽,在每次數據更新後使用匹配規則對請求介面返回的數據列表進行篩選,然後picker綁定篩選後的數據列表,從而實現antd-select-showSearch功能需求。