Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am trying to change the filter by changing the filterKey on a click event, is this possible? Or is there a better way to achieve this?

<a href="#" v-on:click="filterKey = 'all'">All</a>
<a href="#" v-on:click="filterKey = 'nearby'">Nearby</a>

<ul v-for="user in users | filterBy filterKey">
    <li>{{user.name}}</li>
</ul>

data () {
    return {
        filterKey: 'all',
        users: users,
    }
},

filters: {
    all: (users) => {
        return users
    },
    nearby: (users) => {
        return users.filter((users) => {
            return users.distance <= 15
        })
    }

}
share|improve this question
    
Do you only have two filters or do you plan on adding more? It really depends on how flexible you need it to be. – Bill Criswell Apr 22 '16 at 15:44
up vote 1 down vote accepted

You can use computed properties if you'd like to use an approach similar to what you have. You could do something like:

new Vue({
  el: '#app',
  data: {
    userFilterKey: 'all',
    users: [
      { name: 'Bill Close', distance: 10 },
      { name: 'Bill Far', distance: 100 },
      { name: 'Bill Criswell', distance: 1 }
    ]
  },
  computed: {
    userFilter() {
      return this[this.userFilterKey]
    },
    all() {
      return this.users
    },
    nearby() {
      return this.users.filter((user) => user.distance <= 15)
    }
  }
})

Then your template can look something like this:

<div id="app">
  <button v-on:click="userFilterKey = 'all'" :class="{ active: userFilterKey == 'all' }">All</button>
  <button v-on:click="userFilterKey = 'nearby'" :class="{ active: userFilterKey == 'nearby' }">Nearby</button>
  <ul>
    <li v-for="user in userFilter">
      {{ user.name }}
    </li>
  </ul>
</div>

Here's a demo of this in action: https://jsfiddle.net/1f9ytasb/

Though, if you plan on filtering by multiple things it might be easier to create an array of filter critera and just have one filtered computed property that filters out users based on that array of criteria.

share|improve this answer
    
That's exactly what I was looking for. Thank you! – Ruud Luijten Apr 22 '16 at 21:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.