当前位置: 首页 > news >正文

实现一个全栈模糊搜索匹配的功能

提供一个全栈实现的方案,包括 Vue 3 前端、Express 后端和 MySQL 数据库的分类模糊搜索功能。让我们逐步来看:

1. 数据库设计 (MySQL)

首先,我们需要一个存储分类的表:

CREATE TABLE categories (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);-- 插入一些示例数据
INSERT INTO categories (name) VALUES 
('Electronics'), ('Books'), ('Clothing'), ('Home & Garden'), ('Sports');

2. 后端实现 (Express)

安装必要的包

npm install express mysql2

创建数据库连接

// db.js
const mysql = require('mysql2/promise');const pool = mysql.createPool({host: 'localhost',user: 'your_username',password: 'your_password',database: 'your_database',waitForConnections: true,connectionLimit: 10,queueLimit: 0
});module.exports = pool;

实现 Express 路由

// app.js
const express = require('express');
const db = require('./db');
const app = express();app.use(express.json());app.get('/api/categories/search', async (req, res) => {try {const { query } = req.query;const [rows] = await db.query('SELECT * FROM categories WHERE name LIKE ?',[`%${query}%`]);res.json(rows);} catch (error) {console.error(error);res.status(500).json({ error: 'Internal server error' });}
});const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

3. 前端实现 (Vue 3)

创建一个新的 Vue 3 组件

<!-- CategorySearch.vue -->
<template><div><input v-model="searchQuery" @input="searchCategories" placeholder="Search categories..."/><ul><li v-for="category in categories" :key="category.id">{{ category.name }}</li></ul></div>
</template><script>
import { ref } from 'vue';
import axios from 'axios';export default {setup() {const searchQuery = ref('');const categories = ref([]);const searchCategories = async () => {if (searchQuery.value.length > 0) {try {const response = await axios.get(`/api/categories/search?query=${searchQuery.value}`);categories.value = response.data;} catch (error) {console.error('Error fetching categories:', error);}} else {categories.value = [];}};return {searchQuery,categories,searchCategories};}
};
</script>

在主应用中使用组件

<!-- App.vue -->
<template><div id="app"><h1>Category Search</h1><CategorySearch /></div>
</template><script>
import CategorySearch from './components/CategorySearch.vue';export default {name: 'App',components: {CategorySearch}
};
</script>

4. 优化建议

  1. 防抖:在前端实现防抖,避免频繁的 API 调用。
  2. 缓存:考虑在后端实现缓存机制,减少数据库查询。
  3. 分页:如果分类数量很大,考虑实现分页功能。
  4. 索引:在 MySQL 的 categories 表的 name 列上添加索引,提高查询性能。
CREATE INDEX idx_category_name ON categories(name);
  1. 安全性:确保对用户输入进行适当的验证和清理,防止 SQL 注入攻击。

这个实现提供了一个基本的全栈分类模糊搜索功能。您可以根据具体需求进行进一步的定制和优化。如果您有任何问题或需要更详细的解释,请随时告诉我。

注意,MySQL 的 LIKE 操作符默认是不区分大小写的。

http://www.lryc.cn/news/410628.html

相关文章:

  • 智慧景区导览系统小程序开发
  • HIVE调优方式及原因
  • deploy local llm ragflow
  • 测桃花运(算姻缘)的网站系统源码
  • 电商平台优惠券
  • 内衣洗衣机多维度测评对比,了解觉飞、希亦、鲸立哪款内衣洗衣机更好
  • 数据结构和算法入门
  • 基于OpenCV C++的网络实时视频流传输——Windows下使用TCP/IP编程原理
  • (BS ISO 11898-1:2015)CAN_FD 总线协议详解6- PL(物理层)规定3
  • docker环境下php安装扩展步骤 以mysqli为例
  • 医院综合绩效核算系统,绩效核算系统源码,采用springboot+avue+MySQL技术开发,可适应医院多种绩效核算方式。
  • ROOM数据快速入门
  • 刷新,前面接口的返回值没有到,第二个接口已经请求完了,导致第二个接口返回数据错误
  • pdcj设计
  • 【数据结构】哈希表的模拟实现
  • 面试经典算法150题系列-数组/字符串操作之多数元素
  • 海南云亿商务咨询有限公司领航抖音电商服务
  • C#初级——继承
  • Github 2024-07-29 开源项目日报 Top10
  • nginx反向代理和负载均衡+安装jdk-22.0.2
  • 软考高级科目怎么选?软考高级含金量排序
  • 【机器学习西瓜书学习笔记——模型评估与选择】
  • vue3+cesium创建地图
  • Zookeeper客户端和服务端NIO网络通信源码剖析
  • 从DevOps到DevSecOps是怎样之中转变?
  • ORM与第三方数据库对接的探讨及不同版本数据库的影响
  • Windows远程桌面无法拷贝文件问题
  • 优化数据处理效率,解读 EasyMR 大数据组件升级
  • 并发编程AtomicInteger详解
  • ctfshow 权限维持 web670--web679