SQL
CREATE TABLE `notice` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
`title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '标题',
`content` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '内容',
`time` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '发布时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统公告';
开发后端接口
from typing import Optional
from datetime import datetime
from fastapi import APIRouter
from pydantic import create_model, BaseModel
from tortoise.contrib.pydantic import pydantic_model_creator
from common.exception_handler import CustomException
from common.result import Result, PageInfo
from models import Notice
router = APIRouter(prefix="/notice")
NoticePydantic = pydantic_model_creator(Notice)
NoticeCreatePydantic = create_model(
"NoticeCreatePydantic",
**{
name: (Optional[field.annotation], None)
for name, field in NoticePydantic.model_fields.items()
}
)
# 新增
@router.post("/add")
async def add(notice_create_pydantic: NoticeCreatePydantic):
notice_create_pydantic.time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 将参数转换成 字典数据
create_data = notice_create_pydantic.model_dump(exclude_unset=True, exclude={"id"})
await Notice.create(**create_data) # no=xxx,name=xxx,college=xxx
return Result.success()
# 更新
@router.put("/update")
async def add(notice_create_pydantic: NoticeCreatePydantic):
if notice_create_pydantic.id is None:
raise CustomException("缺少参数ID")
# 将参数转换成 字典数据
update_data = notice_create_pydantic.model_dump(exclude_unset=True, exclude={"id"})
await Notice.filter(id=notice_create_pydantic.id).update(**update_data) # no=xxx,name=xxx,college=xxx where id = xxx
return Result.success()
# 删除
@router.delete('/delete/{notice_id}')
async def delete(notice_id: int):
await Notice.filter(id=notice_id).delete()
return Result.success()
# 单个查询
@router.get('/selectById/{notice_id}')
async def select_by_id(notice_id: int):
notice = await Notice.get_or_none(id=notice_id)
return Result.success(notice)
# 查询所有数据
@router.get('/selectAll')
async def select_all(title: str = ""):
notice_list = await Notice.filter(title__contains=title).order_by("-id") # title__contains表示根据name进行模糊查询
return Result.success(notice_list)
# 分页查询数据
@router.get('/selectPage')
async def select_page(title: str = "", pageNum: int = 1, pageSize: int = 10):
query = Notice.filter(title__contains=title) # title__contains表示根据name进行模糊查询
notice_list = await query.order_by("-id").offset((pageNum - 1) * pageSize).limit(pageSize)
total = await query.count()
# notice_list 转成字典数据
notice_dict_list = [
NoticePydantic.model_validate(notice).model_dump()
for notice in notice_list
]
page_info = PageInfo(list=notice_dict_list, total=total)
return Result.success(page_info)
开发前端页面
<template>
<div>
<div class="card" style="margin-bottom: 5px;">
<el-input v-model="data.title" style="width: 300px; margin-right: 10px" placeholder="请输入标题查询"></el-input>
<el-button type="primary" @click="load">查询</el-button>
<el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
</div>
<div class="card" style="margin-bottom: 5px">
<div style="margin-bottom: 10px">
<el-button type="primary" @click="handleAdd">新增</el-button>
</div>
<el-table :data="data.tableData" stripe>
<el-table-column label="名称" prop="title"></el-table-column>
<el-table-column label="内容" prop="content"></el-table-column>
<el-table-column label="发布时间" prop="time"></el-table-column>
<el-table-column label="操作" align="center" width="160">
<template #default="scope">
<el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
<el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="card">
<el-pagination @current-change="load" background layout="total, prev, pager, next" v-model:page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"/>
</div>
<el-dialog title="系统公告信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
<el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="100px" style="padding-right: 50px">
<el-form-item label="标题" prop="title">
<el-input placeholder="请输入标题" v-model="data.form.title" autocomplete="off" />
</el-form-item>
<el-form-item label="内容" prop="content">
<el-input placeholder="请输入内容" type="textarea" :rows="3" v-model="data.form.content" autocomplete="off" />
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="data.formVisible = false">取 消</el-button>
<el-button type="primary" @click="save">保 存</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script setup>
import request from "@/utils/request";
import {reactive, ref} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
const formRef = ref()
const data = reactive({
user: JSON.parse(localStorage.getItem('system-user') || '{}'),
pageNum: 1,
pageSize: 10,
total: 0,
formVisible: false,
form: {},
tableData: [],
title: null,
rules: {
title: [
{ required: true, message: '请输入标题', trigger: 'blur' }
],
content: [
{ required: true, message: '请输入内容', trigger: 'blur' }
],
}
})
// 分页查询
const load = () => {
request.get('/notice/selectPage', {
params: {
pageNum: data.pageNum,
pageSize: data.pageSize,
title: data.title
}
}).then(res => {
data.tableData = res.data?.list
data.total = res.data?.total
})
}
// 新增
const handleAdd = () => {
data.form = {}
data.formVisible = true
}
// 编辑
const handleEdit = (row) => {
data.form = JSON.parse(JSON.stringify(row))
data.formVisible = true
}
// 新增保存
const add = () => {
request.post('/notice/add', data.form).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
data.formVisible = false
} else {
ElMessage.error(res.msg)
}
})
}
// 编辑保存
const update = () => {
request.put('/notice/update', data.form).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
data.formVisible = false
} else {
ElMessage.error(res.msg)
}
})
}
// 弹窗保存
const save = () => {
formRef.value.validate(valid => {
if (valid) {
// data.form有id就是更新,没有就是新增
data.form.id ? update() : add()
}
})
}
// 删除
const handleDelete = (id) => {
ElMessageBox.confirm('删除后数据无法恢复,您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
request.delete('/notice/delete/' + id).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
} else {
ElMessage.error(res.msg)
}
})
}).catch(err => {})
}
// 重置
const reset = () => {
data.title = null
load()
}
// 处理文件上传的钩子
const handleImgSuccess = (res) => {
data.form.avatar = res.data // res.data就是文件上传返回的文件路径,获取到路径后赋值表单的属性
}
load()
</script>