Vue.js结合Laravel API实现列表搜索功能无返回结果问题求助
问题排查
以下是代码中的核心问题:
- 调用Laravel分页接口返回的
teachers是分页对象,真实数据存放在teachers.data数组里,直接对teachers对象调用数组专属的filter方法会直接报错,自然得不到过滤结果。 - 模板渲染列表时用的还是原始的
teachers.data,完全没有用到编写的filterSearch计算属性,搜索操作自然不会生效。 - 搜索匹配逻辑没有做大小写兼容,且在过滤逻辑里额外给
employees赋值属于冗余操作,也会影响过滤判断的正确性。 - 当前采用分页拉取数据的模式,前端搜索默认只能搜索当前页的内容,如果需要全量搜索建议改成后端搜索逻辑,或者一次性拉取全量数据再做前端分页+搜索。
修复后代码
<template> <div class="kt-portlet"> <div class="kt-portlet__body"> <!--begin::Section--> <div class="kt-section"> <label> <input type="text" v-model="searchTerm" placeholder="Search Here"> </label> <div class="kt-section__content"> <table class="table" id="datatable"> <thead> <tr> <th>ID</th> <th>Product Title</th> <th>Product Price</th> <th>Created On</th> </tr> </thead> <tbody> <!-- 改成循环过滤后的计算属性 --> <tr v-for="teacher in filterSearch" :key="teacher.id"> <td>{{teacher.id}}</td> <td>{{teacher.name}}</td> <td>{{teacher.email}}</td> <td>{{teacher.name}}</td> </tr> </tbody> </table> </div> <div class="row "> <div class=""> <pagination :data="teachers" @pagination-change-page="getTeachers"></pagination> </div> </div> </div> </div> </div> </template> <script> export default { data() { return { teachers:{}, searchTerm:'', } }, computed:{ filterSearch(){ // 先判断数据是否存在,避免初始加载报错 if(!this.teachers?.data) return [] const term = this.searchTerm.trim() // 搜索词为空直接返回全部数据 if(!term) return this.teachers.data // 对真实数据数组做过滤,大小写不敏感匹配 return this.teachers.data.filter((teacher) => { return teacher.name.match(new RegExp(term, 'i')) }) } }, methods:{ getTeachers(page = 1) { axios.get("/api/teachers?page=" + page ) .then((response)=> { this.teachers = response.data; }) } }, mounted(){ this.getTeachers(); } } </script>
额外说明
如果需要实现跨分页的全局搜索,建议把搜索词作为参数传给后端接口,由后端做数据库层面的模糊查询返回对应分页结果,前端仅需要在searchTerm变化时调用getTeachers方法,把搜索词拼到请求参数里即可。
内容的提问来源于stack exchange,提问作者Mohamed El Fwakhry
相关产品推荐
相关产品推荐

