当前版本:
- 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文章来源:https://www.toymoban.com/news/detail-679309.html
export default defineEventHandler( async (event) => {
let data = await $fetch(`http://localhost:3002/system/user/${event.context.params?.id}`, {
method:"delete"
})
return data
})
app.vue:文章来源地址https://www.toymoban.com/news/detail-679309.html
<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
到了这里,关于Nuxt3中请求数据-useFetch等的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!