javascript - 一个基本的 Vue JS 搜索过滤器,不区分大小写或仅在数组中小写?

标签 javascript vue.js vuejs2

我在 Vue JS 中制作了一个基本的搜索过滤器,用于根据标题过滤一些博客文章。但是,它引发了一些关于用户如何搜索数组中每个字符串中存储的内容的问题。

例如,将数组中的字符串写成小写是最佳实践吗?

如果不是必需的,那么目前当用户搜索“运动”时不会返回任何内容。但是,如果用户搜索“体育”,则会显示正确的结果。

因此,由于用户在使用搜索输入字段时不知道首字母大写,有没有办法不进行区分大小写的搜索来避免此问题?

      <h1>Blog Search</h1>
      <input type="text" id="search" v-model="search" placeholder="Search blogs">
      <ul>
          <li v-for="blog in filteredBlogs">
             <h2>{{blog.title}}</h2>
          </li>
      </ul>

我的脚本如下

export default {
    data() {
        return {
            search:'',
            blogs: [
              { title: 'How to take photographs' },
              { title: 'Sports from around the world' }
            ]
        };
    },
    computed: {
        filteredBlogs: function(){
            return this.blogs.filter((blog) => {
                return blog.title.match(this.search);
            });
        }
    }
};

最佳答案

首先将您的对象标题转换为小写,然后将您的搜索文本转换为小写然后进行搜索:

export default {
    data() {
        return {
            search:'',
            blogs: [
              { title: 'How to take photographs' },
              { title: 'Sports from around the world' }
            ]
        };
    },
    computed: {
        filteredBlogs: function(){
            return this.blogs.filter((blog) => {
                return blog.title.toLowerCase().match(this.search.toLowerCase());
            });
        }
    }
};

关于javascript - 一个基本的 Vue JS 搜索过滤器,不区分大小写或仅在数组中小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401510/

相关文章:

javascript - 在所有浏览器上,正常缩放时内部 material-ui Chip 组件周围会出现边框,但在放大或缩小时不会出现边框

javascript - AngularJs中如何使用DropDown选中的值作为过滤器的参数?

javascript - 无样式内容 vuejs 的 Flash

html - v-如果没有按预期表现

javascript - 没有 if 的 if 语句

javascript - timeago.js 未按预期工作

javascript - 我的项目使用代理跨域,但是当我请求它的请求地址改变

javascript - Vue.js - 点击跨度也会点击输入。如何防止呢?

javascript - Vue2 v-text 工作不正确

python - 从 django-rest 检索数据以显示在表单中