VueJS中如何利用ES6特性优化计算属性的classes过滤逻辑?
Great question! Let's break down how to clean up this computed property using ES6 features and better logical structure. First, let's fix that tiny typo (haSubjects should be hasSubjects)—easy miss!
Key Optimizations to Apply
1. Cache Repeated Computations
You’re calling this.gradeFilter.map(el => el.value) and this.subjectFilter.map(el => el.value) multiple times inside the filter callback. This is redundant and hurts both performance and readability. We can precompute these value arrays once at the start.
2. Simplify Conditional Logic
Your original four conditional checks can be collapsed into a more intuitive structure. The core idea is:
- If no filters are active, return everything (you already have this)
- Otherwise, a class is valid if it’s the selected class, or it matches all active filters (if a filter isn’t active, it automatically "matches")
3. Use const for Immutable Values
Variables like hasGrades and hasSubjects don’t change after initialization—using const instead of let aligns with ES6 best practices and makes intent clearer.
Optimized Code
filteredClasses() { // Precompute filter value arrays once const gradeValues = this.gradeFilter.map(el => el.value); const subjectValues = this.subjectFilter.map(el => el.value); const hasGrades = gradeValues.length > 0; const hasSubjects = subjectValues.length > 0; const allClasses = _.flatMap(this.classes); // Early return if no filters are active if (!hasGrades && !hasSubjects) return allClasses; return allClasses.filter(x => { // Break down conditions into named variables for readability const isSelectedClass = x.name === this.selectedClass.name; const matchesGrade = !hasGrades || gradeValues.includes(x.grade); const matchesSubject = !hasSubjects || subjectValues.includes(x.subjectId); // Final check: selected class OR matches all active filters return isSelectedClass || (matchesGrade && matchesSubject); }); }
Why This Works Better
- Readability: Each condition has a descriptive name, so anyone reading the code can immediately understand what’s being checked.
- Performance: We avoid re-running
map()on filter arrays for every class in the list. - Maintainability: If you ever need to add more filters (like a teacher filter), you can extend this pattern easily by adding a new
matchesXvariable and updating the final return logic.
As an optional extra: If this.selectedClass could ever be null or undefined, use optional chaining (this.selectedClass?.name) to avoid runtime errors.
内容的提问来源于stack exchange,提问作者yariv bar

