Vue - 在方法中过滤数组时传递过滤条件

时间:2017-11-21 05:38:09

标签: javascript filter vue.js arguments

我试图在渲染之前通过filterCriteria过滤listItems 问题是当我使用Array.prototype.filter时,我无法将filterCriteria传递给过滤器函数。
有没有什么好方法可以在不创建新功能的情况下传递它? 谢谢!

var todoList = new Vue({
	el: '#todolist',
	data: {
    // I want to use filterCriteria in data as filter criteria
		filterCriteria: 'Done',
		listItems: [
			{
				content: 'Fishing.',
				status: 'Done',
			},
			{
				content: 'Do homework.',
				status: 'Ongoing',
			}
		],
	},
	methods: {
		filterList(listItems) {
			return listItems.filter(function(item) {
        // Ideally the 'Ongoing' here should be "filterCriteria" in data property
			  return item.status === 'Ongoing';
			});
		}
	},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
		<div id="todolist">
      <div class="list-filter">
        <a href="#">Ongoing</a>
        <a href="#">Done</a>
      </div>
			<div v-for="item in filterList(listItems)" class="list-item">
				<span class="list-status">{{item.status}}</span>
				<span class="list-content">{{item.content}}</span>
			</div>
		</div>

1 个答案:

答案 0 :(得分:3)

  

...无法将filterCriteria传递给过滤器函数。   有没有什么好方法可以在不创建新功能的情况下传递它?

是的,确实如此。首先,更简单,使用箭头函数进行回调:

filtered () {
  return this.items.filter(item => item.status === this.query)
}

其次,遗留,保存this对象引用:

filtered () {
  var vm = this
  return this.items.filter(function (item) {
    item.status === vm.query
  })
}

完整示例:

&#13;
&#13;
var todoList = new Vue({
  el: '#todolist',
  data: {
    query: 'Done',
    items: [
      {content: 'Fishing.', status: 'Done'},
      {content: 'Do homework.', status: 'Ongoing'}
    ]
  },
  computed: {
    filtered () {
      return this.items.filter(item => item.status === this.query)
    }
  }
})
&#13;
<div id="todolist">
  <div>
    <button @click="query='Ongoing'">Ongoing</button>
    <button @click="query='Done'">Done</button>
  </div>
  <div v-for="item, idx in filtered" :key="idx">
    <span>{{item.status}}:</span>
    <span>{{item.content}}</span>
  </div>
</div>

<script src="https://unpkg.com/vue"></script>
&#13;
&#13;
&#13;