Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Filter list with Vue.js

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">

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.

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

})

Template:

  <div id="app">

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

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

  </div>

Demo: http://jsbin.com/dezokiwowu/edit?html,js,console,output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...