npm地址:https://www.npmjs.com/package/pinyin-match

选择器拼音快速检索目标(pinyin-match)

一. 使用方法

  1. 安装 pinyin-match

    yarn add pinyin-match

    npm install pinyin-match --save

  2. 引入
    import PinYinMatch from 'pinyin-match';
    
  3. 使用

    使用自定义搜索方法 :filter-method="match"

    <el-select
      v-model="value"
      placeholder="请选择"
      filterable
      :filter-method="match"
    >
      <el-option
        v-for="item in filterList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    

    过滤数据 PinYinMatch.match(item.label, val);

    methods: {
      match(val) {
        if (val) {
          let result = [];
          this.list.forEach(item => {
            let matchRes = PinYinMatch.match(item.label, val);
            if (matchRes) {
              result.push(item);
            }
          });
          this.filterList = result;
        } else {
          this.filterList = this.list;
        }
      }
    }
    

二. 使用实例

<template>
  <div>
    <el-select
      v-model="value"
      placeholder="请选择"
      filterable
      :filter-method="match"
    >
      <el-option
        v-for="item in filterList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
import PinYinMatch from "pinyin-match";
export default {
  data() {
    return {
      // 初始数据
      list: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        },
        {
          value: "选项3",
          label: "蚵仔煎"
        },
        {
          value: "选项4",
          label: "龙须面"
        },
        {
          value: "选项5",
          label: "北京烤鸭"
        }
      ],
      // 过滤后的数据
      filterList: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        },
        {
          value: "选项3",
          label: "蚵仔煎"
        },
        {
          value: "选项4",
          label: "龙须面"
        },
        {
          value: "选项5",
          label: "北京烤鸭"
        }
      ],
      value: ""
    };
  },
  methods: {
    match(val) {
      if (val) {
        let result = [];
        this.list.forEach(item => {
          let matchRes = PinYinMatch.match(item.label, val);
          if (matchRes) {
            result.push(item);
          }
        });
        this.filterList = result;
      } else {
        this.filterList = this.list;
      }
    }
  }
};
</script>

<style scoped>
</style>

三. 实现效果

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐