Vue学习笔记04(关键字搜索)

it2023-11-18  70

添加关键字搜索功能

1、在商品信息输入框后面再加一个关键字搜索框

搜索关键字: <input type="text" class="form-control" v-model="keyword" />

2、在data里定义一个keyword变量,然后用v-model绑定到搜索框里

keyword:'', //搜索的关键字

3、定义一个search()方法,把keyword作为参数传进入

先在search()方法里定义一个空数组用foreach()方法遍历list数组,用之前遍历list数组的item作为作为里面箭头函数的参数用indexof()方法判断商品的NAME跟你输入的关键字有没有匹配的字符,也就是判断indexof()方法的返回值是否为-1,为-1则无匹配信息,不为-1则有匹配信息如果不为-1则把匹配的商品信息插入定义的新数组foreach()方法遍历完后,返回新数组

3.1、 search()方法代码

search(keyword){ var newlist = []; this.list.forEach(item=>{ if(item.NAME.indexOf(keyword) != -1){ newlist.push(item); } }) return newlist; }

4、这时,要把利用v-for遍历出来的商品信息所依赖的数组改为search(keyword)方法,因为这个方法最终会返回一个数组

<tr v-for="item in search(keyword)" :key="item.id"> <td>{{item.id}}</td> <td>{{item.NAME}}</td> <td>{{item.CTIME | setdate}}</td> <td><a @click.prevent="del(item.id)">删除</a></td> <!-- prevent清除a链接的默认行为 --> </tr>

4.1、页面效果

*注意:

为什么不输入关键字会显示全部的商品信息呢,这是因为输入为空时,indexof方法返回的值为0,不为-1,所以能显示全部信息,如果输入空格则返回-1
最新回复(0)