How to achieve fuzzy search in layui?
In Layui, there are two ways to achieve a fuzzy search.
- Implement fuzzy search using backend API: Using the data table component of Layui, set the url property to the address of the backend API. Additionally, you can pass the fuzzy search conditions by setting the where parameter. The backend API will perform a fuzzy query based on these conditions and return the results to be displayed on the frontend.
Sample code:
layui.use('table', function(){
var table = layui.table;
table.render({
elem: '#demo',
url: '/api/data', // 后端接口地址
where: {
keyword: '关键字' // 模糊查询的条件
},
cols: [[
{field: 'id', title: 'ID'},
{field: 'name', title: '姓名'},
{field: 'age', title: '年龄'}
]]
});
});
Example of backend API (using Node.js and Express framework):
app.get('/api/data', function(req, res){
var keyword = req.query.keyword; // 获取前端传递的模糊查询条件
// 根据关键字进行模糊查询
var result = data.filter(function(item){
return item.name.includes(keyword);
});
res.json(result);
});
- Implementing fuzzy search using front-end filters: In the Layui data table component, you can set the filter’s name using the lay-filter attribute, then listen for changes in the table data and perform the fuzzy search operation in the callback function.
Sample code:
layui.use('table', function(){
var table = layui.table;
table.render({
elem: '#demo',
url: '/api/data', // 后端接口地址
cols: [[
{field: 'id', title: 'ID'},
{field: 'name', title: '姓名'},
{field: 'age', title: '年龄'}
]],
done: function(res, curr, count){
// 监听数据渲染完成的事件
// 获取输入框的值
var keyword = $('#keyword').val();
// 进行模糊查询
var result = res.data.filter(function(item){
return item.name.includes(keyword);
});
// 渲染过滤后的数据
table.reload('demo', {
data: result
});
}
});
});
HTML code:
<div class="layui-inline">
<input id="keyword" type="text" class="layui-input" placeholder="请输入关键字">
</div>
These are the two ways to implement fuzzy search in Layui, you can choose the one that best fits your specific needs.