直播软件搭建,利用精准搜索优化用户搜索体验

精准搜索

核心思想:将用户输入的字符串作为一个整体去与数组的每一项做匹配,把符合的保存下来即可。

这里主要用到的JavaScript字符串的indexOf()方法——返回某个指定的字符串值在字符串中首次出现的位置,如果不存在,则返回-1。

有一点需要注意,`indexOf()` 方法对大小写敏感! 另外数组也有一个`indexOf()`方法

下面是上述实例的完整代码,当然实际开发的时候数据肯定没这么简单。我们这里使用的是Vue + Element

实现

<template>
  <div class="wrapper">
    <el-input
      clearable
      placeholder="请输入"
      suffix-icon="el-icon-search"
      v-model="searchMsg"
      size="mini"
      @input="handleSearch(searchMsg)"
    ></el-input>
    <el-checkbox-group v-model="checkList">
      <div v-for="(item, index) in filterMsg" :key="index">
        <el-checkbox :label="item">{{ item.name }}</el-checkbox>
      </div>
    </el-checkbox-group>
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchMsg: "",
      checkList: [],
      filterMsg: []
    };
  },
  mounted() {
    this.allMsg = [
      { name: "myhua", id: 1 },
      { name: "mp3", id: 2 },
      { name: "hello", id: 3 },
      { name: "world", id: 4 },
      { name: "warm weather", id: 5 },
      { name: "m3", id: 6 },
      { name: "hahaha", id: 7 }
    ];
    this.filterMsg = this.allMsg;
  },
  methods: {
    // 搜索方法
    handleSearch(queryString) {
      this.filterMsg = [];
      this.allMsg.map(item => {
        if (item.name.indexOf(queryString) !== -1) {
          this.filterMsg.push(item);
        }
      });
    }
  }
};
</script>

另外字符串的search()方法在这里也能实现相同的效果,对大小写敏感
在这里推荐使用includes,这样更语义化一些,自己有点懒这里就没改

posted @ 2024-08-10 08:50  云豹科技-苏凌霄  阅读(2)  评论(0编辑  收藏  举报