2024年1月Java项目开发指南16:用户自由选择字段查询、是否模糊查询
我们希望用户可以自己控制是否要模糊查询
用户可以自由的选择字段去查询。
如上图,我在前端页面准备了
- 多选框:决定是否模糊查询。(True or False)
- 下拉选择框:决定要查询关键词的所属字段
- 输入框:决定关键词
- 按钮:发起请求
肯定要传参数的,所有这个接口请求方式设置为Post。考虑到方便接收参数,我们使用post的param方式传参(不了解这个的可以看我之前的笔记 https://www.cnblogs.com/mllt/p/17990445/project202401-14)
export function user_search(data){
return postWithParams("/users/search",data)
}
现在我们先编写按钮事件 userSearch()
const userSearch=()=>{
//配置参数
let data={
"like":checked.value,//是否模糊查询
"key":ziduan_select.value,//字段名称
"word":keyword.value//关键词
}
//发送请求
user_search(data).then((res)=>{
if(res["code"]===1){
message.success(res["msg"]);
dataSource.value=res["data"]
}else {
message.error(res["msg"]);
}
})
}
接下来去编写后端接口
Controller:
// 条件查询
@PostMapping("/search")
public ResponseEntity<?> searchUsers(@RequestParam boolean like,@RequestParam String key,@RequestParam String word) {
List<Users> users = usersService.searchUsers(like, key, word);
return ResponseEntity.success(users);
}
Service
List<Users> searchUsers(boolean like, String key, String word);
ServiceImpl
@Override
public List<Users> searchUsers(boolean like, String key, String word) {
if(like){
return usersMapper.searchUsersLike(key,word);
}else{
return usersMapper.searchUsersNoLike(key,word);
}
}
mapper
//自定义字段模糊查询
@Select("select * from users where `${key}` LIKE CONCAT('%', #{word}, '%')")
List<Users> searchUsersLike(@Param("key") String key, @Param("word") String word);
@Select("select * from users where `${key}` = #{word}")
List<Users> searchUsersNoLike(String key, String word);
完毕,就是如此简单。
我把前端的这个组件的完整代码贴出来
<script setup>
import {PlusSquareOutlined,SearchOutlined} from "@ant-design/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {user_delete_by_id, user_get_list, user_search, user_update} from "../../../apis/UserApi.js";
import { cloneDeep } from 'lodash-es';
import {message} from "ant-design-vue";
onMounted(()=>{
user_get_list().then((res)=>{
dataSource.value=res.data
//对得到的用户数据进行处理,以显示在表格中
})
})
const columns = [
{
title: '操作',
dataIndex: 'operation',
width: '20%',
},
{
title: '用户ID',
dataIndex: 'userId',
width: '10%',
},
{
title: '昵称',
dataIndex: 'userNickname',
width: '10%',
},
{
title: '账号',
dataIndex: 'userAccount',
width: '10%',
},
{
title: '身份',
dataIndex: 'userIdentity',
width: '10%',
}, {
title: '权限',
dataIndex: 'remarks',
width: '10%',
},
{
title: '注册时间',
dataIndex: 'userRegTime',
width: '25%',
},
];
const dataSource = ref([]);
const editableData = reactive({});
const edit = key => {
editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.userId)[0]);
};
const save = key => {
Object.assign(dataSource.value.filter(item => key === item.userId)[0], editableData[key]);
delete editableData[key];
// 找到要更新的用户的索引
const userIndex = dataSource.value.findIndex(item => key === item.userId)
// 调用更新用户的函数
const updatedUser = dataSource.value[userIndex];
console.log(updatedUser)
user_update(updatedUser)
.then(response => {
// 处理响应,例如显示成功消息
// console.log('User updated successfully', response);
message.success(response["msg"])
})
.catch(error => {
// 处理错误,例如显示错误消息
// console.error('Failed to update user', error);
message.error(error)
});
};
const cancel = key => {
delete editableData[key];
};
const formatDate= (dateTimeStr)=> {
if (dateTimeStr === '' || dateTimeStr==null) {
return ''; // 返回空字符串或者其他占位符
}
// 使用 Date 对象解析日期时间字符串
const date = new Date(dateTimeStr);
// 检查日期对象是否有效
if (isNaN(date.getTime())) {
return ''; // 返回空字符串或者其他占位符
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const checked = ref(true);
const keyword=ref("")
const ziduan_select=ref("user_id")
const ziduan=ref([{
value: 'user_id',
label: '用户ID',
},
{
value: 'user_nickname',
label: '昵称',
},
{
value: 'user_account',
label: '用户账号',
},])
const onDelete = key => {
let uid = key
dataSource.value = dataSource.value.filter(item => item.userId !== key);
user_delete_by_id(uid).then((res)=>{
if(res["code"]===1){
message.success(res["msg"]);
}else {
message.error(res["msg"]);
}
})
};
const userSearch=()=>{
//配置参数
let data={
"like":checked.value,//是否模糊查询
"key":ziduan_select.value,//字段名称
"word":keyword.value//关键词
}
//发送请求
user_search(data).then((res)=>{
if(res["code"]===1){
message.success(res["msg"]);
dataSource.value=res["data"]
}else {
message.error(res["msg"]);
}
})
}
</script>
<template>
<br>
<div class="mytable">
<a-breadcrumb>
<a-breadcrumb-item><a href="/">主页</a></a-breadcrumb-item>
<a-breadcrumb-item><a href="/user">用户管理</a></a-breadcrumb-item>
</a-breadcrumb>
<br>
<hr>
<br>
<a-space>
<a-checkbox v-model:checked="checked">模糊查询</a-checkbox>
<a-select
v-model:value="ziduan_select"
style="width: 100px"
:options="ziduan"
></a-select>
<a-input v-model:value="keyword" placeholder="请输入关键词"/>
<a-button type="primary" @click="userSearch">
<template #icon>
<SearchOutlined />
</template>
搜索
</a-button>
<a-button type="primary" >
<template #icon>
<PlusSquareOutlined />
</template>
新增用户
</a-button>
</a-space>
</div>
<br>
<a-table class="mytable" :columns="columns" :data-source="dataSource" bordered>
<template #bodyCell="{ column, text, record }">
<template v-if="['userNickname', 'userIdentity', 'userStatus','remarks'].includes(column.dataIndex)">
<div>
<a-input
v-if="editableData[record.userId]"
v-model:value="editableData[record.userId][column.dataIndex]"
style="margin: -5px 0"
/>
<template v-else>
{{ text }}
</template>
</div>
</template>
<template v-else-if="column.dataIndex==='userRegTime'">
{{formatDate(text)}}
</template>
<template v-else-if="column.dataIndex === 'operation'">
<div class="editable-row-operations">
<span v-if="editableData[record.userId]">
<a-typography-link @click="save(record.userId)" style="margin: 14px">保存</a-typography-link>
<a-popconfirm style="margin: 14px" title="放弃更改?" ok-text="放弃" cancel-text="取消" @confirm="cancel(record.userId)">
<a>取消</a>
</a-popconfirm>
</span>
<span v-else>
<a @click="edit(record.userId)">编辑</a>
</span>
</div>
<a-popconfirm
v-if="dataSource.length"
title="确认删除?"
ok-text="确定" cancel-text="取消"
@confirm="onDelete(record.userId)"
>
<a>删除</a>
</a-popconfirm>
</template>
</template>
</a-table>
</template>
<style scoped>
.mytable{
margin: 0 auto;max-width: 960px;width: 90%; border-radius:5px;box-shadow: 0 5px 15px 2px rgba(0,0,0,0.2);padding: 1em;box-sizing: border-box;background: rgba(255,255,255,0.9)
}
</style>
版 权 声 明
作者:萌狼蓝天
QQ:3447902411(仅限技术交流,添加请说明方向)
转载请注明原文链接:https://www.cnblogs.com/mllt/p/18000149/project202401-16