我在 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/