【问题标题】:Filter array of a computed property using a method in Vue.js使用 Vue.js 中的方法过滤计算属性的数组
【发布时间】:2021-06-28 17:22:00
【问题描述】:

我希望这不是一个愚蠢的问题。我有一个列出 ALL 课程的计算属性。当用户单击一个调用名为 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'])
        }
    }

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

【问题讨论】:

    标签: javascript vue.js filter vuejs2 computed-properties


    【解决方案1】:

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

    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 的输出 + 当前状态。

    另外请注意,我将计算属性命名为名词而不是动词,我发现这使代码更容易理解。

    【讨论】:

      猜你喜欢
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2018-07-11
      • 2019-08-04
      • 2022-11-20
      • 1970-01-01
      相关资源
      最近更新 更多