在点击事件vue.js上更改过滤器

时间:2016-04-22 14:57:26

标签: vue.js

我试图通过更改click事件的filterKey来更改过滤器,这可能吗?或者有更好的方法来实现这一目标吗?

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

}

1 个答案:

答案 0 :(得分:3)

如果您想使用类似于您拥有的方法,则可以使用计算属性。你可以这样做:

foreach ($master_schedule as &$_ms)
{
  $current_soak_time = $_ms['between_starts'] - $_ms['total_run_time'];
  if ($current_soak_time > 0)
  {
      $new_soak_time = ceil($current_soak_time * 0.9);
      unset($master_schedule['between_starts']);
      $_ms['between_starts'] = $_ms['total_run_time'] + $new_soak_time;
      $watering_window['total_run_time'] -= $current_soak_time - $new_soak_time;
  }

}

然后你的模板看起来像这样:

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

以下是此操作的演示:https://jsfiddle.net/1f9ytasb/

但是,如果您计划按多个事项进行过滤,则可能更容易创建过滤器标准数组,并且只有一个<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> 计算属性可根据该标准数组过滤掉用户。