使用Vue.js中的方法筛选计算属性的数组



我希望这不是一个愚蠢的问题。我有一个计算属性,列出了所有课程。当用户单击调用一个名为courseFilters((的方法的按钮时,我希望将计算的属性过滤为显示未存档的课程。

这是我计算的属性:

filterCourses() {
const getUser = this.$store.getters['UserData/getUser']

return this.courses.filter((item) => {
if(this.checkAuthorization(['leader'])) {
return item.createdBy === getUser.uid
} else {
return item
}
})
}

这是我的方法:

courseFilters(which) {
if(which == 'hide-archived') {
this.filterCourses.filter((item) => {
if(!item.archive) {
return item
}
})
}
if(which == 'clear') {
this.getCourses(this.$store.getters['AppData/cid'])
}
}

当前,当我单击按钮时,计算的属性没有任何变化。

我不认为我完全理解你的问题的细节,但这里有一个可能会启发你的解决方案的草图:

export default {
data() {
return { areArchivedCoursesVisible: false };
},
computed: {
authorizedCourses() {
const getUser = this.$store.getters['UserData/getUser'];
// The callback in a filter should return true or false.
// I'm not sure if this is exactly what you want.
// If your original code works, then skip this.
return this.courses.filter(
(c) => this.checkAuthorization(['leader']) && c.createdBy === getUser.uid
);
},
visibleCourses() {
// This is probably what you display in your template.
// It's either all of the authorized courses, or the authorized
// courses which are not archived.
return this.areArchivedCoursesVisible
? this.authorizedCourses
: this.this.authorizedCourses.filter((c) => !c.archive);
},
},
methods: {
toggleVisible() {
// Toggle between showing and not showing the archived courses
this.areArchivedCoursesVisible = !this.areArchivedCoursesVisible;
},
},
};

这只是保持一些状态,指示是否应该显示存档的课程(通过方法切换(。然后,您可以结合计算的属性,根据状态得到正确的答案。在本例中,visibleCourses使用计算属性authorizedCourses的输出+当前状态。

还要注意,我将计算属性命名为名词,而不是动词,这使代码更容易理解。

最新更新