前后端交互-搜索框模糊查询

前后端交互-搜索框模糊查询

记录一下常见功能前后端交互的搜索框模糊查询。

大致思路:当前端点击搜索功能,获取到搜索框内的内容,携带请求的参数向后端发送网络请求,后端接收到网络请求,根据前端带来请求参数,根据次参数进行数据库语句查询。

交互流程

前端–>后端:给搜索按钮添加点击事件,跳转路由来到搜索页,并携带参数key

1
2
3
4
5
6
this.$router.push({
name:'list',
query:{
key:this.searchVal
}
})

跳转路由后创建组件时调用请求接口函数:将路由携带的参数传递给后端。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
created(){
this.getData()
},
methods:{
getData(){
http.$axios({
url:'/api/goods/shopList',
params:{
searchName:this.$route.query.key
}
}).then(res=>{
this.goodsList=res
console.log(res);
})
}
}

http.$axios为二次封装的axios,具体操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import axios from 'axios'
// 引入mint-ui里的Indicator,在相应数据时出现小动画
import {Indicator} from 'mint-ui'
export default {
common:{
method:'GET',
data:{},
params:{}
},
$axios(option={}){
option.method = option.method || this.common.method;
option.data = option.data || this.common.data;
option.params = option.params || this.common.params;

Indicator.open('加载中...')
return axios(option).then(v=>{
let data = v.data.data
return new Promise((res,rej)=>{
if(!v) return rej()
Indicator.close()
res(data)
})
})
}
}

后端接收前端请求里的数据参数(使用express框架):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var express = require('express');
var router = express.Router();
// 引入连接数据库
var connection = require('../db/sql.js')
// 查询搜索接口
router.get('/api/goods/shopList',function(req,res,next){
let searchName= req.query.searchName
// 模糊查询
connection.query('select * from goods_list where name like "%'+searchName+'%"',function(err,results){
console.log(err);
// 返回匹配到的数据给前端
res.send({
code:0,
data:results
})
})
})

连接数据库:

1
2
3
4
5
6
7
8
const mysql = require('mysql')
let connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'admin123',
database:'vue-tea-store'
})
module.exports = connection;

这里连接时报错,查了原因是因为MySQL 8.0默认的密码验证模式,与node的默认密码验证模式不一致导致无法连接数据库报错。

解决办法:修改验证模式

打开终端,输入以下命令和密码,连接MySQL。

1
mysql -u root -p

输入以下SQL语句,修改验证模式和密码。

1
ALTER USER "root"@"localhost" IDENTIFIED WITH mysql_native_password BY "password";

输入以下SQL语句,刷新权限,使修改立即生效。

1
FLUSH PRIVILEGES;

退出MySQL。

1
exit;

前端根据相应的数据进行渲染。

1
2
3
4
5
6
7
8
9
10
11
getData(){
http.$axios({
url:'/api/goods/shopList',
params:{
searchName:this.$route.query.key
}
}).then(res=>{
this.goodsList=res
console.log(res);
})
}

拿到响应数据赋值给this.goodsList,列表根据 this.goodsList进行数据渲染。


前后端交互-搜索框模糊查询
http://example.com/2023/09/19/前后端交互-搜索框模糊查询/
作者
AlongSunsea
发布于
2023年9月19日
许可协议