[Vuejs]-VueJS: Display filtered array list

0👍

You should only have 1 computed object. This can have multiple computed properties inside:

computed: {
  deceasedAuthors() {return ...},
  livingAuthors() {return ...},
}

These can be shortened to this:

  computed: {
    alive() {
      return this.authors.filter(author => !author.deceased)
    },
    deceased() {
      return this.authors.filter(author => author.deceased)
    }
  },

You can get the number of objects in an array using .length:

alive.length
deceased.length

Here is a fully working example: Vue SFC Playground

<template>
  <div>
    Alive
  </div>
  <ul>
    <li v-for="(author, key) in alive" :key="key">
        {{author.name}} - {{author.birthYear}}
    </li>
    <li>Total: {{alive.length}}</li>
  </ul>
  <div>
    Deceased
  </div>
  <ul>
    <li v-for="(author, key) in deceased" :key="key">
        {{author.name}} - {{author.birthYear}}
    </li>
    <li>Total: {{deceased.length}}</li>
  </ul>
</template>

<script>
import { defineComponent } from "vue";
export default defineComponent({
  computed: {
    alive() {
      return this.authors.filter(author => !author.deceased)
    },
    deceased() {
      return this.authors.filter(author => author.deceased)
    }
  },
  data(){
    return {
       authors: [
        {
            name: 'Edgar Allan Poe',
            birthYear: 1809,
            deceased: true
        },
        {
            name: 'Dr. Seuss',
            birthYear: 1896,
            deceased: true
        },
        {
            name: 'Margaret Atwood',
            birthYear: 1939,
            deceased: false
        },
        {
            name: 'Robert Frost',
            birthYear: 1874,
            deceased: true
        },
        {
            name: "Alice Walker",
            birthYear: 1944,
            deceased: false,
        },
        {
            name: "J.K. Rowling",
            birthYear: 1965,
            deceased: false,
        },
        {
            name: "Jonathan Swift",
            birthYear: 1745,
            deceased: true,
        },
        {
            name: "George R.R. Martin",
            birthYear: 1948,
            deceased: false,
        },
        {
            name: "Jane Austen",
            birthYear: 1817,
            deceased: true,
        },
        {
            name: "Stephen King",
            birthYear: 1809,
            deceased: false,
        }
     
    ]
    }
  }
});
</script>

Leave a comment