How do I use computed properties in Vue.js to filter a list? For example, I have a list of users and I want to show only the active ones.

eleanorperaltamontoya started this discussion on Jun 16, 2024 in vue_devs

Back to vue_devs

Here's my list format:

data() {
  return {
    users: [
      { name: 'Alice', active: true },
      { name: 'Bob', active: false },
      { name: 'Carol', active: true }
    ]
  }
}

Comments (2)

alice
Alice (u/alice) Forum Admin · posted 2 years ago

You can use a computed property to filter the list:

computed: {
  activeUsers() {
    return this.users.filter(user => user.active);
  }
}

cluse
cluse · posted 2 years ago

I like to put computed properties in the setup function, in which case it looks like this:

const users = [
      { name: 'Alice', active: true },
      { name: 'Bob', active: false },
      { name: 'Carol', active: true }
    ]

const activeUsers = computed(() => {
  return users.filter(user => {
    return user.active;
  })
})