使用属性 监视 对数组进行 过滤 显示
1、定义数组数据,字段包含id name age address
data: {
searchWord: "",
persons: [
{"id": "001", "name": "张三", "age": 19, "address": "北京"},
{"id": "002", "name": "李四", "age": 29, "address": "南京"},
{"id": "003", "name": "王五", "age": 16, "address": "深圳"},
{"id": "004", "name": "麻子", "age": 26, "address": "广州"},
{"id": "005", "name": "刘二", "age": 38, "address": "上海"}
],
persons_1: []
},
2、定义一个搜索框
<input type="text" v-model:value="searchWord">
3、定义一个展示列表,这里采用ul -> li形式进行循环输出
<ul>
<li class="h3" v-for="person in persons_1" :key="person.id">
{{person.id}} > {{person.name}} > {{person.age}} > {{person.address}}
</li>
</ul>
4、定义监视属性,方法为searchWord,
immediate:true : 意思是不等搜索框值变化先执行一遍,应对刚开始内容为空,不产生变化而导致的不执行的问题
this.persons.filter((p):js的命令,过滤器的意思
p.name.indexOf(Value) != -1:判断name里面有没有value字符串,如果-1代表没有
watch: {
searchWord: {
immediate:true,
handler(Value) {
this.persons_1 = this.persons.filter((p) => {
return p.name.indexOf(Value) != -1
})
}
}
}
5、结果展示:
6、源码截图