Vue.js中品牌过滤后按product.name字母序排序实现求助
解决方案
在你的过滤逻辑后添加数组排序方法即可,同时优化结果计数的写法:
export default { data() { return { filteredProducts: [] }; }, mounted() { axios .get('/src/stores/sneakers.json') .then(response => (this.filteredProducts = response.data)) }, computed: { resultCount () { // 数组直接通过length属性获取结果数量,无需Object.keys return this.filteredList.length }, filteredList(){ return this.filteredProducts .filter(product => product.brand.includes(this.brand?.name)) // 按name字段字母序排序,统一转小写消除大小写影响 .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())) } }, }
关键说明:
- 使用
localeCompare()做字符串比较,比直接用>或<更稳定,能正确处理带特殊字符的字符串,适配多语言排序规则。 - 统一转为小写是为了避免大小写差异导致的排序异常(比如默认排序中"Z"会排在"a"前面)。
内容的提问来源于stack exchange,提问作者chrisjarn
相关产品推荐
相关产品推荐

