Vue中列表过滤
作者:互联网
文章目录
列表过滤,可以用以下两种方法实现,
- 使用watch。
- 使用computed。
使用watch
- 第一次实现
<body>
<div id="root">
<input type="text" v-model="keyWord">
<ul>
<li v-for="(p,index) of persons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.gender}}-{{index}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el:"#root",
data:{
keyWord:'',
persons:[
{id:"001",name:"周冬雨",age:18,gender:"女"},
{id:"002",name:"马冬梅",age:19,gender:"女"},
{id:"003",name:"张桂梅",age:19,gender:"女"},
{id:"004",name:"周杰伦",age:20,gender:"男"}
]
},
watch:{
keyWord:{
handler(val){
this.persons = this.persons.filter((p) => {
return p.name.indexOf(val)!==-1;
})
}
}
}
})
</script>
</body>
- 第二次实现
添加了filterPersons。
<body>
<div id="root">
<input type="text" v-model="keyWord">
<ul>
<li v-for="(p,index) of filterPersons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.gender}}-{{index}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el:"#root",
data:{
keyWord:'',
persons:[
{id:"001",name:"周冬雨",age:18,gender:"女"},
{id:"002",name:"马冬梅",age:19,gender:"女"},
{id:"003",name:"张桂梅",age:19,gender:"女"},
{id:"004",name:"周杰伦",age:20,gender:"男"}
],
filterPersons:[]
},
watch:{
keyWord:{
handler(val){
this.filterPersons = this.persons.filter((p) => {
return p.name.indexOf(val)!==-1;
})
}
}
}
})
</script>
</body>
- 第三次实现
添加了immediate:true,一刷新页面就调用回调。
<body>
<div id="root">
<input type="text" v-model="keyWord">
<ul>
<li v-for="(p,index) of filterPersons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.gender}}-{{index}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el:"#root",
data:{
keyWord:'',
persons:[
{id:"001",name:"周冬雨",age:18,gender:"女"},
{id:"002",name:"马冬梅",age:19,gender:"女"},
{id:"003",name:"张桂梅",age:19,gender:"女"},
{id:"004",name:"周杰伦",age:20,gender:"男"}
],
filterPersons:[]
},
watch:{
keyWord:{
immediate:true,
handler(val){
this.filterPersons = this.persons.filter((p) => {
return p.name.indexOf(val)!==-1;
})
}
}
}
})
</script>
</body>
使用computed
<body>
<div id="root">
<input type="text" v-model="keyWord">
<ul>
<li v-for="(p,index) of filterPersons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.gender}}-{{index}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip = false;
new Vue({
el:"#root",
data:{
keyWord:'',
persons:[
{id:"001",name:"周冬雨",age:18,gender:"女"},
{id:"002",name:"马冬梅",age:19,gender:"女"},
{id:"003",name:"张桂梅",age:19,gender:"女"},
{id:"004",name:"周杰伦",age:20,gender:"男"}
],
},
computed:{
filterPersons(){
return this.persons.filter((p) => {
return p.name.indexOf(this.keyWord)!==-1;
})
}
}
})
</script>
</body>
标签:Vue,name,gender,age,列表,persons,过滤,id 来源: https://blog.csdn.net/qzw752890913/article/details/122722622