Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  186] [ 3]  / answers: 1 / hits: 95488  / 8 Years ago, sun, january 22, 2017, 12:00:00

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 ?


More From » vue.js

 Answers
2

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


[#59249] Friday, January 20, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
corie

Total Points: 371
Total Questions: 110
Total Answers: 113

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
corie questions
Mon, Feb 22, 21, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Sun, Jun 9, 19, 00:00, 5 Years ago
;