web123456

【Learn a little a day-05】Use the Vant component-picker selector in Vue and add search function to the selector

  • <template>
  • <van-picker
  • title="title"
  • :columns="searchColumns" //Data list
  • >
  • <template #title>//#title is displayed in the picker-title position
  • <van-field
  • v-model="searchKey"//Bidirectional binding data
  • placeholder="Please enter search content"
  • clearable
  • />
  • </template>
  • </van-picker>
  • </template>
  • <script>
  • import { Picker, Field } from 'vant'//Reference Vant component
  • export default {
  • name: 'demo',
  • data() {
  • return {
  • columns: [],   //The component uses data list, and will not change after initialization
  • searchColumns: [],//Search for filtered data list, as the query content changes
  • }
  • },
  • mounted() { //Initialize the data
  • this.getList();//Load the page to get data
  • },
  • methods: {
  • /* Method for getting data list */
  • async getList() {
  • try{
  • const { res } = await = getList(); //Request the encapsulation interface
  • const { code, msg, data } = res;//The interface returns data
  • if( code === 200){
  • this.columns = data;//Save data
  • this.searchColumns = data;//Initialize the data for the query array
  • }
  • } catch( e ) { throw new Error( msg ) }
  • }
  • },
  • watch: { //Real-time monitoring of search input content
  • searchKey: function () {
  • let key = String( this.searchKey );
  • key = key.replace( /\s*/g, "" );//Remove spaces in search content
  • const reg = new RegExp( key, "ig" ); //Matching rules -i: Ignore case, g: Global match
  • /* Filter and put the filtered data into a new array. The ‘name’ key can be adjusted according to the key you need to search */
  • this.searchColumns = this.columns.filter( item => item.name.match( reg ) !=null );
  • }
  • }
  • }
  • </script>
  • <style lang="less" scoped>
  • </style>