Jason
Jason

Reputation: 1151

Filter array of a computed property using a method in Vue.js

I hope this is not a stupid question. I have a computed property that lists ALL courses. When the user clicks a button calling a method called courseFilters() I would like to filter the computed property to only show Courses that are not archived.

Here is my computed property:

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
                }
            })
        }

Here is my Method:

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'])
        }
    }

Currently when I click the button nothing changes to the computed property.

Upvotes: 0

Views: 2338

Answers (1)

David Weldon
David Weldon

Reputation: 64342

I don't think I fully understand the details of your problem, but here's a sketch for a solution that may inspire you:

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;
    },
  },
};

This just holds some state indicating if the archived courses should be shown (toggled via a method). Then you can combine your computed properties to get the correct answer based on the state. In this example, visibleCourses uses the output of the computed property authorizedCourses + the current state.

Also note that I named the computed properties as nouns and not verbs, which I find makes the code much easier to understand.

Upvotes: 1

Related Questions