vue node实现模糊搜索
实现模糊搜索的基本思路
模糊搜索通常涉及前端输入关键词,后端处理查询并返回匹配结果。Vue负责用户界面和请求发送,Node.js处理后端逻辑和数据库查询。
前端Vue实现
创建搜索输入框和结果展示组件:
<template>
<div>
<input v-model="searchQuery" @input="handleSearch" placeholder="输入关键词...">
<ul v-if="results.length">
<li v-for="item in results" :key="item.id">{{ item.name }}</li>
</ul>
<p v-else>无匹配结果</p>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
results: []
}
},
methods: {
async handleSearch() {
if (this.searchQuery.length < 2) return
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
} catch (error) {
console.error('搜索出错:', error)
}
}
}
}
</script>
后端Node.js实现
使用Express框架创建API端点:
const express = require('express')
const app = express()
const mongoose = require('mongoose')
// 连接数据库
mongoose.connect('mongodb://localhost:27017/search-demo')
// 定义数据模型
const ItemSchema = new mongoose.Schema({
name: String
})
const Item = mongoose.model('Item', ItemSchema)
// 搜索API
app.get('/api/search', async (req, res) => {
const { q } = req.query
try {
const results = await Item.find({
name: { $regex: q, $options: 'i' }
})
res.json(results)
} catch (err) {
res.status(500).json({ error: err.message })
}
})
app.listen(3000, () => console.log('服务器运行中...'))
数据库模糊查询优化
对于MongoDB,可以使用以下方式优化模糊查询:
// 创建文本索引
Item.createIndex({ name: 'text' })
// 使用文本搜索
const results = await Item.find({
$text: { $search: q }
})
性能优化建议
实现防抖减少请求频率:
// Vue组件中添加
import _ from 'lodash'
export default {
methods: {
handleSearch: _.debounce(async function() {
// 搜索逻辑
}, 300)
}
}
对于大规模数据,考虑使用Elasticsearch等专业搜索引擎替代数据库原生查询。
前端展示优化
添加加载状态和错误处理:
<template>
<div>
<input v-model="searchQuery" @input="handleSearch">
<p v-if="loading">搜索中...</p>
<p v-if="error">{{ error }}</p>
<!-- 结果展示 -->
</div>
</template>
<script>
export default {
data() {
return {
loading: false,
error: null
}
},
methods: {
async handleSearch() {
this.loading = true
this.error = null
try {
// 请求逻辑
} catch (err) {
this.error = '搜索失败,请重试'
} finally {
this.loading = false
}
}
}
}
</script>






