欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 实现一个全栈模糊搜索匹配的功能

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

2024/10/23 23:24:27 来源:https://blog.csdn.net/weixin_41196185/article/details/140739632  浏览:    关键词:实现一个全栈模糊搜索匹配的功能

提供一个全栈实现的方案,包括 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 操作符默认是不区分大小写的。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com