DEV Community

Discussion on: Click Event Filtering on a JSON Rendered List in Vue.js

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I'm not sure but this also could be like this:

<template>
  <div>
    <div>
      <button
        v-for="(entry, index) in filterList"
        :item="entry"
        :key="index"
        @click="
          filter = entry;
          active = index;
        "
        :class="{ active: entry == filter }"
      >
        {{ entry }}
      </button>
    </div>
    <ul class="userWrap">
      <li v-for="(entry, index) in users" :key="index" class="user">
        <h2 class="title">{{ entry.name }}</h2>
        <span class="language"
          >Primary Language: <strong>{{ entry.mainLanguage }}</strong></span
        >
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "DataDisplay",
  data: function() {
    return {
      fkey: "mainLanguage",
      filterList: ["JavaScript", "Python", "PHP", "Java", "All"],
      filter: "All",
      users: [],
      fetchedUsers: []
    };
  },
  created() {
    var apiURL = "https://next.json-generator.com/api/json/get/4JCnNiTCr";
    fetch(apiURL)
      .then(res => res.json())
      .then(res => (this.fetchedUsers = res))
      .catch(error => console.log(error));
  },
  watch: {
    fetchedUsers: function() {
      this.users = this.fetchedUsers;
    },
    filter: function(val, oldVal) {
      this.users =
        val != "All"
          ? this.fetchedUsers.filter(f => f.mainLanguage === val)
          : this.fetchedUsers;
    }
  }
};
</script>

I used watch property.

Collapse
 
apparentlyquiet profile image
Sushant Joshi

I was expecting to read a similar implementation 😅
I guess separating all the filtering logic from markup feels more maintainable to me.