列表过滤可以认为是模糊搜索。实现的下面的这种效果:
1.监视属性watch实现
参考代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue测试</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="root">
<input type="text" placeholder="请输入关键词" v-model="keyWord">
<div>
<li v-for="i in list2">
{{i.name}} --{{i.sex}}--{{i.age}}
</li>
</div>
</div>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
keyWord: "",
list: [
{ "name": "张三1", "sex": "男", "age": 12 },
{ "name": "李四", "sex": "女", "age": 31 },
{ "name": "张三2", "sex": "男", "age": 43 },
{ "name": "王五", "sex": "男", "age": 13 },
{ "name": "五六", "sex": "男", "age": 13 }
],
list2: [] //用来筛选数据
},
//使用watch进行过滤
watch: {
keyWord: {
immediate: true,// 一开始执行进行空过滤
handler(val) {
this.list2 = this.list.filter((i) => {
console.log("keyword被修改", val)
return i.name.indexOf(val) != -1
})
}
}
}
})
</script>
</body>
</html>
需要注意的点:
1.尽量不要使用原数组进行过滤筛选,有可能你过滤筛选后赋值给原数组会导致原数组数据越来越少。
2.immediate:true是为了一开始加载就实行一次空筛选。
3.list是原数组,list2是筛选后数组。
2.用计算属性实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue测试</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="root">
<input type="text" placeholder="请输入关键词" v-model="keyWord">
<div>
<li v-for="i in list2">
{{i.name}} --{{i.sex}}--{{i.age}}
</li>
</div>
</div>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
keyWord: "",
list: [
{ "name": "张三1", "sex": "男", "age": 12 },
{ "name": "李四", "sex": "女", "age": 31 },
{ "name": "张三2", "sex": "男", "age": 43 },
{ "name": "王五", "sex": "男", "age": 13 },
{ "name": "五六", "sex": "男", "age": 13 }
],
},
//计算属性实现
computed:{
list2(){
return this.list.filter((i) => {
return i.name.indexOf(this.keyWord) != -1
})
}
}
})
</script>
</body>
</html>
很明显,计算属性的写法更加简洁,所以遇到这种情况一般使用计算属性来进行筛选。