FastAPI+VUE3创建一个项目的步骤模板(二)

接上文

修改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>

将上面的内容替换原文件。

相关推荐
GIS之路15 分钟前
GDAL 实现矢量裁剪
前端·python·信息可视化
IT=>小脑虎21 分钟前
Python零基础衔接进阶知识点【详解版】
开发语言·人工智能·python
智航GIS23 分钟前
10.6 Scrapy:Python 网页爬取框架
python·scrapy·信息可视化
清水白石0081 小时前
解构异步编程的两种哲学:从 asyncio 到 Trio,理解 Nursery 的魔力
运维·服务器·数据库·python
山海青风1 小时前
图像识别零基础实战入门 1 计算机如何“看”一张图片
图像处理·python
彼岸花开了吗1 小时前
构建AI智能体:八十、SVD知识整理与降维:从数据混沌到语义秩序的智能转换
人工智能·python·llm
山土成旧客2 小时前
【Python学习打卡-Day40】从“能跑就行”到“工程标准”:PyTorch训练与测试的规范化写法
pytorch·python·学习
闲人编程2 小时前
消息通知系统实现:构建高可用、可扩展的企业级通知服务
java·服务器·网络·python·消息队列·异步处理·分发器
大神君Bob2 小时前
【AI办公自动化】如何使用Pytho让Excel表格处理自动化
python
Heorine2 小时前
数学建模 绘图 图表 可视化(6)
python·数学建模·数据可视化