本文介绍了使用Vue.js过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Vue.js,这就是我正在做的事情:我正在渲染产品列表,每个产品都有名称,a 性别尺寸。我希望用户能够按性别过滤产品,方法是输入以输入性别。

I just got started with Vue.js and here is what I'm doing: I am rendering a list of products, and each product has a name, a gender and a size. I'd like users to be able to filter products by gender, by using an input to type the gender.

var vm = new Vue({
      el: '#product_index',
      data: {
        gender: "",
        products: [{name: "jean1", gender: "women", size: "S"}, {name: "jean2", gender: "men", size: "S"}]
      },
      methods:{
        updateGender: function(event){
          this.gender = $(event.target).val()
        }
      }
    }
  )

  <div v-for="product in products" v-if="...">
    <p>{{product.name}}<p>
  </div>
  <input v-on:change="updateGender">

我设法更新了性别,但我对过滤部分有疑问。页面加载时,我不希望任何过滤。在文档中,他们建议使用 v-if 但它似乎与此配置不兼容。

I managed to get the gender updated, but I have an issue with the filtering part. When the page loads, I don't want any filtering. In the documentation, they advise to use v-if but it doesn't seem compatible with this configuration.

如果我使用 v-if ,我可以这样做:

If I use v-if, I could do:

v-if="product.gender == gender"

但是再一次,当页面不起作用时加载,因为性别是空的。
我无法找到解决方法。

But again, this doesn't work when the page load because gender is empty.I couldn't find a workaround for this.

我该如何处理这个问题?

How should I approach this issue ?

推荐答案

使用计算属性 - 像这样的东西(按类型过滤示例)

Use computed properties - something like this (Example bellow filter items by type)

const app = new Vue({

  el: '#app',

  data: {
     search: '',
     items: [
       {name: 'Stackoverflow', type: 'development'},
       {name: 'Game of Thrones', type: 'serie'},
       {name: 'Jon Snow', type: 'actor'}
     ]
  },

  computed: {
    filteredItems() {
      return this.items.filter(item => {
         return item.type.toLowerCase().indexOf(this.search.toLowerCase()) > -1
      })
    }
  }

})

模板:

  <div id="app">

    <div v-for="item in filteredItems" >
      <p>{{item.name}}<p>
    </div>

    <input type="text" v-model="search">

  </div>

演示:

这篇关于使用Vue.js过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:54