接上文
修改VUE内容
打开文件 vue-frontend/src/App.vue,用以下代码替换其内容。我们使用浏览器的原生 fetch API 进行请求:
<script setup>
import { ref, onMounted } from 'vue';
// ------------------------------------
// 1. 定义状态和常量
// ------------------------------------
const tasks = ref([]); // 存放从后端获取的任务列表
const newTaskTitle = ref(''); // 存储输入框的内容
const apiBaseUrl = 'http://127.0.0.1:8000'; // FastAPI 后端地址
// ------------------------------------
// 2. 获取任务的函数 (Read - 读取)
// ------------------------------------
async function fetchTasks() {
try {
const response = await fetch(`${apiBaseUrl}/tasks`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
tasks.value = await response.json();
} catch (error) {
console.error("获取任务失败:", error);
alert('无法连接到 FastAPI 后端!请确保后端服务已运行在 http://127.0.0.1:8000');
}
}
// ------------------------------------
// 3. 增加新任务 (Create - 创建)
// ------------------------------------
async function addTask() {
if (!newTaskTitle.value.trim()) {
alert('任务标题不能为空!');
return;
}
const taskData = {
// ID 不需要提供,FastAPI 会自动分配
title: newTaskTitle.value,
is_completed: false
};
try {
const response = await fetch(`${apiBaseUrl}/tasks`, {
method: 'POST', // 使用 POST 方法
headers: {
'Content-Type': 'application/json', // 告诉后端我们发送的是 JSON
},
body: JSON.stringify(taskData), // 将 JavaScript 对象转换为 JSON 字符串发送
});
if (response.ok) {
const createdTask = await response.json();
tasks.value.push(createdTask); // 将新创建的任务(包含后端分配的ID)添加到前端列表
newTaskTitle.value = ''; // 清空输入框
} else {
throw new Error('创建任务失败');
}
} catch (error) {
console.error("创建任务时发生错误:", error);
alert('创建任务失败,请检查后端连接。');
}
}
// ------------------------------------
// 4. 切换任务完成状态 (Update - 更新)
// ------------------------------------
async function toggleTask(task) {
// 1. 立即在前端切换状态 (乐观更新)
const newState = !task.is_completed;
// 2. 准备发送给后端的数据
const updatedTaskData = {
id: task.id,
title: task.title,
is_completed: newState // 发送新的状态
};
try {
const response = await fetch(`${apiBaseUrl}/tasks/${task.id}`, {
method: 'PUT', // 使用 PUT 方法进行全量更新
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedTaskData),
});
if (response.ok) {
// 3. 如果成功,更新本地状态
task.is_completed = newState;
} else {
// 4. 如果失败,回滚本地状态并报错
throw new Error(`更新任务状态失败, 状态码: ${response.status}`);
}
} catch (error) {
console.error(`更新任务 ${task.id} 失败:`, error);
alert('更新任务失败,请检查后端连接。');
// 如果请求失败,保持任务原有状态
}
}
// ------------------------------------
// 5. 删除任务 (Delete - 删除)
// ------------------------------------
async function deleteTask(taskId) {
if (!confirm('确定要删除这个任务吗?')) {
return;
}
try {
const response = await fetch(`${apiBaseUrl}/tasks/${taskId}`, {
method: 'DELETE', // 使用 DELETE 方法
});
if (response.ok) {
// 1. 如果后端删除成功,在前端列表中过滤掉该任务
tasks.value = tasks.value.filter(t => t.id !== taskId);
} else {
// 2. 如果后端返回 404 等,则抛出错误
throw new Error(`删除任务失败, 状态码: ${response.status}`);
}
} catch (error) {
console.error(`删除任务 ${taskId} 失败:`, error);
alert('删除任务失败,请检查后端连接。');
}
}
// ------------------------------------
// 6. 生命周期钩子
// ------------------------------------
// 组件挂载后立即调用 fetchTasks
onMounted(fetchTasks);
</script>
<template>
<div class="container">
<h1>📝 FastAPI & Vue 3 任务列表</h1>
<div class="add-task-form">
<input type="text" v-model="newTaskTitle" @keyup.enter="addTask" placeholder="输入新的任务标题..." />
<button @click="addTask">添加任务</button>
</div>
<ul class="task-list" v-if="tasks.length">
<li v-for="task in tasks" :key="task.id" :class="{ completed: task.is_completed }">
<span class="title" @click="toggleTask(task)">
{{ task.title }}
</span>
<button class="delete-btn" @click="deleteTask(task.id)">
删除
</button>
</li>
</ul>
<p v-else class="empty-message">
🎉 当前没有任务。快创建一个吧!
</p>
<p class="status-info">
已成功连接到后端:**{{ apiBaseUrl }}**
</p>
</div>
</template>
<style>
/* 样式部分保持一致性 */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f0f2f5;
color: #333;
}
.container {
max-width: 600px;
margin: 50px auto;
background: white;
padding: 30px;
border-radius: 12px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #42b883; /* Vue 绿色 */
margin-bottom: 25px;
}
.add-task-form {
display: flex;
gap: 10px;
margin-bottom: 25px;
}
.add-task-form input {
flex-grow: 1;
padding: 12px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 16px;
}
.add-task-form button {
background-color: #42b883;
color: white;
border: none;
padding: 12px 20px;
border-radius: 6px;
cursor: pointer;
white-space: nowrap;
transition: background-color 0.2s;
}
.add-task-form button:hover {
background-color: #369c6b;
}
.task-list {
list-style: none;
padding: 0;
}
.task-list li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 18px;
margin-bottom: 10px;
background: #fcfcfc;
border-radius: 6px;
border-left: 5px solid #42b883;
transition: all 0.3s;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.task-list li.completed {
opacity: 0.6;
border-left-color: #aaa;
background: #f4f4f4;
}
.title {
cursor: pointer;
flex-grow: 1;
font-size: 1.1em;
}
.task-list li.completed .title {
text-decoration: line-through;
}
.delete-btn {
background-color: #ff4d4f;
color: white;
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
}
.delete-btn:hover {
background-color: #d9363e;
}
.empty-message {
text-align: center;
padding: 20px;
color: #666;
font-style: italic;
}
.status-info {
margin-top: 30px;
padding-top: 15px;
border-top: 1px solid #eee;
font-size: 0.85em;
text-align: center;
color: #999;
}
</style>
将上面的内容替换原文件。