Nuxt3中请求数据-useFetch等
作者:小教学发布时间:2023-09-29分类:程序开发学习浏览:85
导读:当前版本:Nuxt 3.4.1Nitro:2.3.3效果图 Nuxt接口~/server/api里面的文件会自动在路由中加上/api的前缀。对于...
当前版本:
- Nuxt 3.4.1
- Nitro:2.3.3
效果图
Nuxt接口
~/server/api
里面的文件会自动在路由中加上/api
的前缀。对于不需要带/api
前缀的服务器路由,可以把它们放到~/server/routes
目录中。
查:/server/api/user.ts
export default defineEventHandler( async (event) => {
let query = getQuery(event)
let data = await $fetch("http://localhost:3002/system/user", {
query
})
return data
})
增:/server/api/user.post.ts
export default defineEventHandler( async (event) => {
const body = await readBody(event)
let data = await $fetch("http://localhost:3002/system/user", {
method: "post",
body
})
return data
})
改:/server/api/user.put.ts
export default defineEventHandler( async (event) => {
const body = await readBody(event)
let data = await $fetch("http://localhost:3002/system/user", {
method: "put",
body
})
return data
})
删:/server/api/user/[id].delete.ts
export default defineEventHandler( async (event) => {
let data = await $fetch(`http://localhost:3002/system/user/${event.context.params?.id}`, {
method:"delete"
})
return data
})
app.vue:
<template>
<client-only>
<el-button type="primary" @click="openAddDialog">新增</el-button>
<el-input v-model="state.searchByUsername" clearable placeholder="输入用户名称搜索" style="width: 400px; margin: 0 10px" />
<el-button type="success" @click="searchUser">搜索</el-button>
<el-table :data="state.tableData" style="width: 100%">
<el-table-column label="用户名" prop="username" width="180"></el-table-column>
<el-table-column label="密码" width="180">
<template #default="scope">
<el-tag>{{ scope.row.password }}</el-tag>
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :destroy-on-close="true" v-model="state_dialog.isShow" :title="state_dialog.type == 'add' ? '新增' : '编辑'">
<el-form ref="ref_form" :model="state_dialog.form" :rules="state_dialog.rules">
<el-form-item label="用户名" label-width="140px" prop="username">
<el-input v-model="state_dialog.form.username" clearable autocomplete="off" />
</el-form-item>
<el-form-item label="密码" label-width="140px" prop="password">
<el-input v-model="state_dialog.form.password" clearable autocomplete="off" />
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="state_dialog.isShow = false">取消</el-button>
<el-button type="primary" @click="submitForm(ref_form)">确定</el-button>
<el-button type="primary" @click="resetForm(ref_form)">重置</el-button>
</span>
</template>
</el-dialog>
</client-only>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
const ref_form = ref(null);
const state = reactive({
searchByUsername: "",
tableData: [
// {
// id: 1,
// username: "张三",
// password: 333,
// },
// {
// id: 2,
// username: "李四",
// password: 444,
// },
],
});
// 获取用户列表
const getUserList = async () => {
let data = await useFetch("/api/user");
console.log("data:", data)
state.tableData = data.data.value.data;
};
getUserList();
// 根据username查询用户
const searchUser = async () => {
let data = await useFetch("/api/user", {
params: {
username: state.searchByUsername,
},
});
state.tableData = data.data.value.data;
};
// 重置表单
const resetForm = (formName: any) => {
formName.resetFields();
};
// 打开新增窗口
const openAddDialog = () => {
console.log("新增")
state_dialog.isShow = true;
state_dialog.type = "add";
state_dialog.form = {
id: "",
username: "",
password: "",
};
};
// 打开编辑窗口
const handleEdit = (index: number, row: any) => {
console.log("row:", row)
state_dialog.isShow = true;
state_dialog.type = "edit";
state_dialog.form = {
id: row.id,
username: row.username,
password: row.password,
};
};
// 删除用户
const handleDelete = async (index: any, row: any) => {
await useFetch(`/api/user/${row.id}`, {
method: "delete",
});
getUserList();
};
const validator_password = (rule: any, value: any, callback: any) => {
if (!value) {
return callback(new Error("请输入密码"));
}
else {
callback();
}
};
// 弹窗
const state_dialog = reactive({
isShow: false,
type: "add", //edit
form: {
id: "",
username: "",
password: "",
},
rules: {
username: [
{
required: true,
message: "用户名不能为空",
trigger: "blur",
},
{ min: 1, max: 5, message: "长度1到5", trigger: "blur" },
],
password: { validator: validator_password, trigger: "blur" },
},
});
// 提交
const submitForm = (formName: any) => {
formName.validate(async (valid: any) => {
if (valid) {
if (state_dialog.type == "add") {
await useFetch("/api/user", {
method: "post",
body: {
username: state_dialog.form.username,
password: state_dialog.form.password,
}
});
}
if (state_dialog.type == "edit") {
await useFetch("/api/user", {
method: "put",
body: {
id: state_dialog.form.id,
username: state_dialog.form.username,
password: state_dialog.form.password,
}
});
}
state_dialog.isShow = false;
getUserList();
} else {
console.log("error submit!");
return false;
}
});
};
</script>
node接口
const router = require('koa-router')()
const db = require("../db.js")
router.prefix('/system/user')
//根据用户名检查用户是否已存在。注意:这种接口尽量防止靠前一点,放得靠后可能无法触发该接口
router.get('/existence', async (ctx, next) => {
let { username } = ctx.request.query
let sql = `select * from sys_user where username='${username}'`
let users = await db.query(sql);
if (users.length !== 0) {
ctx.body = {
code: 0,
message: "用户已存在",
data: {
isExist_user: true
}
}
} else {
ctx.body = {
code: 0,
message: "用户未存在",
data: {
isExist_user: false
}
}
}
})
//修改用户
router.put('/', async (ctx, next) => {
let { id, username, password } = ctx.request.body
let sql = `update sys_user set password='${password}',username='${username}' where id='${id}'`
await db.query(sql);
ctx.body = {
code: 0,
message: "success",
}
})
//添加用户
router.post('/', async (ctx, next) => {
let { username, password } = ctx.request.body
console.log("ctx.request.body:", ctx.request.body)
let sql = `insert into sys_user(username,password) values ('${username}','${password}')`
await db.query(sql);
ctx.body = {
code: 0,
message: "success",
}
})
//根据username模糊查询用户,若username不存在或为空,则查询所有用户
router.get('/', async (ctx, next) => {
let { username } = ctx.request.query
let sql = `select * from sys_user`
if (username) {
sql += ` where username like '%${username}%'`
}
console.log("sql:", sql)
let users = await db.query(sql);
ctx.body = {
code: 0,
message: "success",
data: users
}
})
//根据id删除用户
router.delete('/:id', async (ctx, next) => {
let { id } = ctx.params
let sql = `delete from sys_user where id='${id}'`
await db.query(sql);
ctx.body = {
code: 0,
message: "success",
}
})
// router.delete('/', async (ctx, next) => {
// let { id } = ctx.request.query
// let sql = `delete from sys_user where id='${id}'`
// await db.query(sql);
// ctx.body = {
// code: 0,
// message: "success",
// }
// })
module.exports = router
- 程序开发学习排行
-
- 1鸿蒙HarmonyOS:Web组件网页白屏检测
- 2HTTPS协议是安全传输,为啥还要再加密?
- 3HarmonyOS鸿蒙应用开发——数据持久化Preferences
- 4记解决MaterialButton背景颜色与设置值不同
- 5鸿蒙HarmonyOS实战-ArkUI组件(RelativeContainer)
- 6鸿蒙HarmonyOS实战-ArkUI组件(Stack)
- 7鸿蒙HarmonyOS实战-ArkUI组件(GridRow/GridCol)
- 8[Android][NDK][Cmake]一文搞懂Android项目中的Cmake
- 9鸿蒙HarmonyOS实战-ArkUI组件(mediaquery)
- 最近发表
-
- WooCommerce最好的WordPress常用插件下载博客插件模块的相关产品
- 羊驼机器人最好的WordPress常用插件下载博客插件模块
- IP信息记录器最好的WordPress常用插件下载博客插件模块
- Linkly for WooCommerce最好的WordPress常用插件下载博客插件模块
- 元素聚合器Forms最好的WordPress常用插件下载博客插件模块
- Promaker Chat 最好的WordPress通用插件下载 博客插件模块
- 自动更新发布日期最好的WordPress常用插件下载博客插件模块
- WordPress官方最好的获取回复WordPress常用插件下载博客插件模块
- Img to rss最好的wordpress常用插件下载博客插件模块
- WPMozo为Elementor最好的WordPress常用插件下载博客插件模块添加精简版