VueJS中数组按艺术家姓名字母排序的问题求助
Solution for Alphabetical Sort by Artist Name in Vue.js
Hey there! Let's get your artist cards sorted alphabetically by name—here's a straightforward fix for your code:
Step 1: Add Sorting Logic to Your Computed Property
Your filteredCategory computed property already handles filtering cards by category. We just need to add a sorting step after the filtering is done.
The main things to keep in mind:
- Use
slice()to create a copy of the filtered array first (sincesort()modifies the original array, and we don't want to alter your originalcardsdata) - Convert artist names to lowercase with
toLowerCase()so the sorting isn't case-sensitive (e.g., "Booba" won't come before "cardi B" just because of capitalization)
Here's the updated filteredCategory computed property:
computed: { filteredCategory: function () { let self = this; let cardsArray = self.cards; let selectedType = self.selectedType; // Filter logic remains the same if (selectedType !== "All") { cardsArray = cardsArray.filter(function (card) { return ( card.type.indexOf(selectedType) !== -1 || card.day.indexOf(selectedType) !== -1 || card.hour.indexOf(selectedType) !== -1 || card.stage.indexOf(selectedType) !== -1 ); }); } // Add alphabetical sorting by artist name return cardsArray.slice().sort((a, b) => { const artistA = a.artist.toLowerCase(); const artistB = b.artist.toLowerCase(); if (artistA < artistB) return -1; if (artistA > artistB) return 1; return 0; }); }, },
How This Works
slice(): Creates a shallow copy of the filtered array, so we don't mutate the originalcardsdata in your Vue instance.sort()with comparison function: Compares each artist's name (converted to lowercase) to ensure consistent alphabetical order, regardless of uppercase/lowercase letters.
Testing It Out
Once you update the computed property, your cards will automatically sort alphabetically by artist name—whether you're viewing all categories or a filtered subset. No extra buttons or setup needed!
内容的提问来源于stack exchange,提问作者Alan RAOUL
相关产品推荐
相关产品推荐

