VUE和Element-UI下拉框select实现拼音,中文搜索

需求:用户要求打出首字母就能搜索到内容,而不是打汉字。

环境:node 14   vue2  vue-cli 4.5

需求分析:element自带搜索功能,支持汉字搜索,拼音的话需要引入第三方插件了。经过实验 pinyin-match完美实现。

解决过程:

首先安装 npm install pinyin-match --save

全局引用和局部引用皆可,这里我们使用了局部引用
import pinyin from "pinyin-match";

下边是全部代码

<template>
  <div class="meteorology">
    <div>输入 cq 看效果</div>
    <!-- value-key :但绑定对象时必须传 -->
    <el-select
      ref="select"
      clearable
      size="mini"
      filterable
      :filter-method="pinyingMatch"
      @visible-change="visibleChange"
      value-key="id"
      v-model="searchVal"
    >
      <el-option
        v-for="item in curList"
        :key="item.id"
        :label="item.stnm + '(' + item.id + '-' + item.stcd + ')'"
        :value="item"
      ></el-option>
    </el-select>
    <div>{{ searchVal }}</div>
    <el-divider></el-divider>
  </div>
</template>

<script>
import pinyin from 'pinyin-match';

export default {
  name: 'meteorology',
  components: {},
  props: {},
  data() {
    return {
      searchVal: null,
      alllist: [
        { id: '1', stcd: '1', stnm: '四川' },
        { id: '2', stcd: '2', stnm: '北京' },
        { id: '3', stcd: '3', stnm: '江西' },
        { id: '4', stcd: '4', stnm: '广东' },
        { id: '5', stcd: '5', stnm: '河南' },
        { id: '6', stcd: '8', stnm: '河北' },
        { id: '7', stcd: '6', stnm: '重庆' },
        { id: '8', stcd: '7', stnm: '广西' },
        { id: '9', stcd: '6', stnm: '出去' },
      ],
      curList: [],
      timer: null,
    };
  },

  mounted() {},
  computed: {},
  watch: {},
  created() {},

  methods: {
    // 模糊查询逻辑 加入了 timer 防抖
    pinyingMatch(value) {
      if (this.timer) clearTimeout(this.timer);

      this.timer = setTimeout(() => {
        // 有值时才执行过滤

        if (value) {
          //搜索到相应的数据进行显示
          this.curList = this.alllist.filter((item) => pinyin.match(item.stnm, value));
        }
      }, 500);
    },
    visibleChange(val) {
      if (val) {
        this.curList = this.alllist.slice(0, 3);
      }
    },
  },
};
</script>

<style scoped lang="less">
.meteorology {
  height: 100%;
}
</style>

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值