从 web03(POST 新增 + 示例改名/删除)到 web04(完整房间 CRUD + 设备放入房间 + 第一个子组件)
你已经完成了 web03:查询 + POST 新增房间(真实后端),以及浏览器内存里的示例改名和删除。 本周 web04 做了两件大事: ① 把房间改名和删除也接到真实后端了(兑现第三周"第四周周一接"的承诺), ② 引入"设备"概念和子组件 DeviceCard.vue,练习 Vue 3 的组件通信三件套。
| 文件 | web03 | web04 |
|---|---|---|
roomApi.js | request('/api/rooms', ...) 写死路径;只有 GET + POST | request(path, ...) 动态路径;GET + POST + PATCH + DELETE 完整 CRUD |
roomSamples.js | 有 renameSampleRoom / deleteSampleRoom / deviceCount | 删除(改名/删除已接真实后端) |
deviceSamples.js | —(不存在) | 新增:3 台示例灯 + moveSampleDeviceTo + resetSampleDevices |
components/DeviceCard.vue | —(不存在) | 新增:第一个子组件,defineProps/defineEmits/watch |
App.vue | api tab 查+新增;practice tab 改名/删示例房间 | api tab 查+增+改+删全真实;practice tab 设备移动示例 |
style.css | .danger / .confirm / .edit-form | 追加 .device-board / .device-card / .sample-toolbar / .room-tabs |
老师给了新的 roomApi.js / style.css / vite.config.js,加了 deviceSamples.js 和 DeviceCard.vue。roomSamples.js 不再需要了。
npm install(如果依赖没跟上)src/roomSamples.js —— 改名/删除不再在示例里做了// src/roomApi.js — 老师提供:request 带 path 参数,支持完整 CRUD async function request(path, options = {}) { let response try { response = await fetch(path, { ...options, headers: { Accept: 'application/json', ...(options.body ? { 'Content-Type': 'application/json' } : {}) } }) } catch { throw new Error('无法连接后端,请确认后端已启动。') } const body = await response.json().catch(() => null) if (!response.ok) throw new Error(body?.message || `接口失败(${response.status})`) if (body?.code !== 'OK') throw new Error('接口响应格式不正确。') return body.data } const validRoom = room => room && typeof room.id === 'string' && typeof room.name === 'string' export async function queryRooms() { const data = await request('/api/rooms') if (!Array.isArray(data) || !data.every(validRoom)) throw new Error('查询应返回含 id、name 的房间数组。') return data } export async function createRoom(name) { const data = await request('/api/rooms', { method: 'POST', body: JSON.stringify({ name }) }) if (!validRoom(data)) throw new Error('新增响应缺少 id、name,请先查询确认保存结果。') return data } // ✨ 本周新增:PATCH /api/rooms/:id export async function renameRoom(id, name) { const data = await request( `/api/rooms/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ name }) } ) if (!validRoom(data) || data.id !== id) throw new Error('改名响应不正确,请重新查询确认结果。') return data } // ✨ 本周新增:DELETE /api/rooms/:id export async function deleteRoom(id) { const data = await request( `/api/rooms/${encodeURIComponent(id)}`, { method: 'DELETE' } ) // DELETE 后端成功后返回 null,检查一下 if (data !== null) throw new Error('删除响应不正确,请重新查询确认结果。') }
request({...options, body, ...}),path 写死 '/api/rooms'。web04 里把 path 提成第一个参数,这样 renameRoom('/api/rooms/abc-123', ...) 就能命中带 id 的路由了。
// src/deviceSamples.js — 独立示例,不发真实请求 const rooms = [ { id: 'sample-room-01', name: '客厅' }, { id: 'sample-room-02', name: '卧室' }, { id: 'sample-room-03', name: '书房' }, ] const initial = [ { id: 'sample-lamp-living', type: 'LAMP', name: '客厅灯', roomId: 'sample-room-01', online: true, state: { power: true } }, { id: 'sample-lamp-desk', type: 'LAMP', name: '床头灯', roomId: 'sample-room-02', online: true, state: { power: false } }, { id: 'sample-lamp-spare', type: 'LAMP', name: '备用灯', roomId: null, online: true, state: { power: false } }, ] const copy = device => ({ ...device, state: { ...device.state } }) let devices = initial.map(copy) export function listSampleRooms() { return rooms.map(r => ({ ...r })) } export function listSampleDevices() { return devices.map(copy) } // ✨ 移动设备位置。roomId = null 表示移回设备池 export async function moveSampleDeviceTo(id, roomId) { const device = devices.find(item => item.id === id) if (!device) throw new Error('设备不存在。') if (roomId !== null && !rooms.some(room => room.id === roomId)) throw new Error('房间不存在。') device.roomId = roomId return copy(device) } export function resetSampleDevices() { devices = initial.map(copy) }
state 对象: 设备除了基本字段(id / type / name / online),还有一个嵌套的 state: { power: true/false }。copy 函数特意写深拷贝({ ...device, state: { ...device.state } }),避免外层对象是新的但 state 还是同一个引用。
先建文件夹 src/components/,再新建 DeviceCard.vue:
<script setup> import { ref, watch, computed } from 'vue' // 三件套 ①:defineProps 接收父组件传进来的参数 const props = defineProps({ device: { type: Object, required: true }, rooms: { type: Array, required: true }, busy: Boolean, }) // 三件套 ②:defineEmits 声明要给父组件发什么事件 const emit = defineEmits(['move']) // 三件套 ③:watch —— props.device.roomId 变化时,同步到本地 ref const targetRoom = ref(props.device.roomId ?? '') watch(() => props.device.roomId, value => { targetRoom.value = value ?? '' }) // computed 派生:用 roomId 找到房间名字,找不到就是"设备池" const location = computed(() => props.rooms.find(room => room.id === props.device.roomId)?.name ?? '设备池' ) function save() { // select 空选项的值是 '',接口约定用 null 表示"移回设备池" emit('move', { id: props.device.id, roomId: targetRoom.value === '' ? null : targetRoom.value, }) } </script> <template> <article class="device-card"> <div class="device-heading"> <h3>{{ device.name }}</h3> <span>灯</span> </div> <p class="device-id">{{ device.id }}</p> <p class="device-state">状态:{{ device.state.power ? '开启' : '关闭' }} · {{ device.online ? '在线' : '离线' }}</p> <p class="device-location">当前位置:{{ location }}</p> <form class="device-form" @submit.prevent="save"> <label :for="`target-${device.id}`">放到哪里</label> <div> <select :id="`target-${device.id}`" v-model="targetRoom" :aria-label="`给${device.name}选择房间`" :disabled="busy"> <option value="">设备池</option> <option v-for="room in rooms" :key="room.id" :value="room.id">{{ room.name }}</option> </select> <button class="primary" :disabled="busy || targetRoom === (device.roomId ?? '')">保存位置</button> </div> </form> </article> </template>
defineProps({ ... }) —— 接收参数(父 → 子 单向只读)defineEmits(['xxx']) —— 声明事件(子 → 父 发信号)watch(propRef, cb) —— props 变化时同步到本地 ref(因为不能直接 v-model props.device.roomId)props.device.roomId = 'xxx'(ESLint 会报错)。所以把它"镜像"到本地 ref targetRoom,用户在 select 里改 targetRoom,提交时 emit 给父组件处理真正的更新。
style.css —— 用 web04 的版本覆盖(末尾多了 .device-board / .device-card / .sample-toolbar / .room-tabs 等设备相关样式)。
vite.config.js —— proxy target 改成 process.env.W04_API_TARGET || 'http://127.0.0.1:8080'(变量名 W04 了)。
npm run dev 能正常启动,控制台无红色报错老师把 apiRooms 重构成"全真实 CRUD",practice tab 换成设备移动。脚手架里保留 busy / runAction / chooseRoom / loadRooms 等工具函数,只留 4 处 BEGIN/END 让你填。
<script setup> import { computed, ref } from 'vue' import { queryRooms, createRoom, renameRoom, deleteRoom } from './roomApi.js' import { listSampleRooms, listSampleDevices, moveSampleDeviceTo, resetSampleDevices } from './deviceSamples.js' import DeviceCard from './components/DeviceCard.vue' // ========== 已给定:所有状态 ========== const step = ref('api') const apiRooms = ref([]) const apiLoaded = ref(false) const apiLoading = ref(false) const apiError = ref('') const newName = ref('') const renameName = ref('') const selectedId = ref('') const saving = ref(false) const formError = ref('') const message = ref('') const pendingDelete = ref(null) // ✨ 本周新增:practice tab 的示例数据 const sampleRooms = listSampleRooms() // 房间是静态示例数组(没有 ref) const sampleDevices = ref(listSampleDevices()) const sampleRoomId = ref('sample-room-03') // practice tab 查看哪个房间 // ========== 已给定:computed ========== const selectedRoom = computed(() => apiRooms.value.find(r => r.id === selectedId.value)) const busy = computed(() => saving.value || apiLoading.value) // ✨ 本周新增:设备分组 —— "设备池" + "选中的房间" const sampleGroups = computed(() => [ { title: '设备池', roomId: null }, { title: sampleRooms.find(r => r.id === sampleRoomId.value)?.name ?? '房间', roomId: sampleRoomId.value }, ]) // ✨ 本周新增:过滤出某个房间(或设备池)下的设备 function devicesAt(roomId) { return sampleDevices.value.filter(d => d.roomId === roomId) } // ========== 已给定:工具函数 ========== function clearNotice() { formError.value = ''; message.value = '' } function chooseRoom(id) { selectedId.value = id renameName.value = selectedRoom.value?.name ?? '' pendingDelete.value = null } function changeStep(value) { if (!busy.value) { step.value = value; pendingDelete.value = null; clearNotice() } } // ========== 已给定:读取后端 ========== async function loadRooms(preferredId = '') { apiLoading.value = true; apiLoaded.value = false apiError.value = ''; apiRooms.value = [] chooseRoom('') try { apiRooms.value = await queryRooms() apiLoaded.value = true chooseRoom(apiRooms.value.some(r => r.id === preferredId) ? preferredId : (apiRooms.value[0]?.id ?? '')) } catch (error) { apiError.value = error.message || '读取失败' } finally { apiLoading.value = false } } // ========== 已给定:POST 新增(web03 上一周的代码,保留不动) ========== async function appendApiRoom() { const created = await createRoom(newName.value) newName.value = '' message.value = `已新增"${created.name}"。` await loadRooms(created.id) } // ========== ⬇⬇⬇ 以下 4 处是你要填的!⬇⬇⬇ ========== async function renameApiRoom() { // BEGIN W04-V1-RENAME // 学生填这里:调 PATCH 真实改名 + 重新查询后端 // END W04-V1-RENAME } async function removeApiRoom(id) { // BEGIN W04-V1-DELETE // 学生填这里:调 DELETE 真实删除 + 选中处理 + 重新查询 // END W04-V1-DELETE } async function moveSampleDevice({ id, roomId }) { await runAction(async () => { // BEGIN W04-V3 // 学生填这里:调 deviceSamples.moveSampleDeviceTo + 刷新 + 构造消息 // END W04-V3 }) } // ========== 已给定:通用包装 / 删除确认 / 重置 ========== async function runAction(action) { if (busy.value) return clearNotice(); saving.value = true try { await action() } catch (error) { formError.value = error.message || '操作失败。' } finally { saving.value = false } } function askDelete() { if (selectedRoom.value && !busy.value) { clearNotice(); pendingDelete.value = { ...selectedRoom.value } } } async function confirmDelete() { const target = pendingDelete.value if (target) await runAction(() => removeApiRoom(target.id)) pendingDelete.value = null } function resetPractice() { resetSampleDevices() sampleDevices.value = listSampleDevices() sampleRoomId.value = 'sample-room-03' clearNotice() } </script>
注意 BEGIN W04-V2 是模板里的标记块——用 DeviceCard 子组件替换原来的占位。
<template> <main class="home"> <header class="page-header"> <div><p class="eyebrow">智能家居 · 第 4 周</p><h1>设备放入房间</h1></div> <p class="week-note">先接房间接口,再练设备位置</p> </header> <nav class="steps" aria-label="本课步骤"> <button :aria-pressed="step === 'api'" :disabled="busy" @click="changeStep('api')">1. 房间接口对接</button> <button :aria-pressed="step === 'practice'" :disabled="busy" @click="changeStep('practice')">2. 设备放入房间</button> </nav> <section class="workspace" aria-label="本课练习"> <!-- =========== API Tab:真实后端 CRUD =========== --> <template v-if="step === 'api'"> <div class="section-head"> <div> <h2>接入房间改名和删除</h2> <p class="source-note">真实后端 · 查询、新增、改名、删除</p> </div> <button class="secondary" :disabled="busy" @click="loadRooms()">{{ apiLoading ? '读取中…' : '读取房间' }}</button> </div> <p class="help">启动后端(端口 8080)。操作成功后重新查询,避免手动刷新页面。</p> <form class="room-form" novalidate @submit.prevent="runAction(appendApiRoom)"> <div class="field"> <label for="new-name">新房间名称</label> <input id="new-name" v-model="newName" maxlength="20" :disabled="busy" placeholder="未使用的房间名称"> </div> <button class="primary" :disabled="busy">新增房间</button> </form> <p v-if="apiError" class="alert" role="alert">{{ apiError }}</p> <p v-if="!apiLoaded && !apiLoading" class="empty">点击"读取房间"查看后端数据。</p> </template> <!-- =========== Practice Tab:设备移动示例 =========== --> <template v-else> <div class="section-head"> <div> <h2>把备用灯放进书房</h2> <p class="source-note sample-note">独立示例 · 第五周周一接真实设备接口</p> </div> <button class="secondary" :disabled="busy" @click="resetPractice">重置示例</button> </div> <div class="sample-toolbar"> <p>总设备数:{{ sampleDevices.length }}。移动位置不会改变 id 和状态。</p> <div class="room-tabs" aria-label="查看示例房间"> <button v-for="room in sampleRooms" :key="room.id" :aria-pressed="sampleRoomId === room.id" :disabled="busy" @click="sampleRoomId = room.id"> {{ room.name }}({{ devicesAt(room.id).length }}) </button> </div> </div> </template> <p v-if="formError" class="alert" role="alert">{{ formError }}</p> <p v-if="message" class="success" role="status">{{ message }}</p> <!-- API tab:房间列表 + 改名/删除表单 + 确认框(和 web03 类似) --> <template v-if="step === 'api' && apiLoaded"> <div class="room-summary"> <p>共 {{ apiRooms.length }} 个房间</p> <p>当前选择:{{ selectedRoom?.name || '未选择' }}</p> </div> <div v-if="apiRooms.length" class="room-list"> <button v-for="room in apiRooms" :key="room.id" class="room-card" :aria-pressed="selectedId === room.id" :disabled="busy || !!pendingDelete" @click="chooseRoom(room.id)"> <strong>{{ room.name }}</strong> <span class="room-id">{{ room.id }}</span> <span class="selected-label">{{ selectedId === room.id ? '已选中' : '点击选择' }}</span> </button> </div> <p v-else class="empty">当前没有房间。</p> <form v-if="selectedRoom" class="room-form edit-form" novalidate @submit.prevent="runAction(renameApiRoom)"> <div class="field"> <label for="rename-name">修改房间名称</label> <input id="rename-name" v-model="renameName" maxlength="20" :disabled="busy || !!pendingDelete"> </div> <button class="primary" :disabled="busy || !!pendingDelete">保存改名</button> <button class="danger" type="button" :disabled="busy || !!pendingDelete" @click="askDelete">删除房间</button> </form> <div v-if="pendingDelete" class="confirm" role="alertdialog"> <p id="delete-title">删除"{{ pendingDelete.name }}"?</p> <p>只可删除空房间,成功后才更新列表。</p> <button class="danger" :disabled="busy" @click="confirmDelete">确认删除</button> <button class="secondary" :disabled="busy" @click="pendingDelete = null">取消</button> </div> </template> <!-- =========== Practice Tab:设备 board(两张卡并排) =========== --> <div v-if="step === 'practice'" class="device-board"> <section v-for="group in sampleGroups" :key="group.roomId ?? 'pool'" class="device-group"> <h2>{{ group.title }} {{ devicesAt(group.roomId).length }} 台</h2> <!-- BEGIN W04-V2 — 用 DeviceCard 子组件循环渲染 --> <!-- 学生填这里 --> <!-- END W04-V2 --> <p v-if="!devicesAt(group.roomId).length" class="empty"> {{ group.roomId === null ? '设备池里没有空闲设备。' : '这个房间还没有设备。' }} </p> </section> </div> </section> <footer>房间操作连接真实后端。设备位置练习使用独立示例,不控制灯的开关。</footer> </main> </template>
第三周承诺的"第四周周一接真实接口"——兑现。和上一步 POST 新增的套路一样:调 API → 提示 → 重新查询。
async function renameApiRoom() { // BEGIN W04-V1-RENAME const renamed = await renameRoom(selectedId.value, renameName.value) message.value = `已改名为"${renamed.name}"。` await loadRooms(renamed.id) // END W04-V1-RENAME }
和改名不同,删除要考虑"选中 id"的处理:如果删的正好是 selectedId,重新查询后应该清空选中,否则继续选中原来的。
async function removeApiRoom(id) { // BEGIN W04-V1-DELETE await deleteRoom(id) // 如果删的是当前选中的房间,loadRooms('') 不会选中任何东西 const nextId = selectedId.value === id ? '' : selectedId.value message.value = '房间已删除。' await loadRooms(nextId) // END W04-V1-DELETE }
之前所有 UI 都是 App.vue 里写 v-for + button,现在换成"for 循环里放子组件标签 + 传 props + 监听 emit 事件"的模式。
<!-- 在每个 device-group section 里,空位置填下面这段 --> <DeviceCard v-for="device in devicesAt(group.roomId)" :key="device.id" :device="device" :rooms="sampleRooms" :busy="saving" @move="moveSampleDevice" />
v-for="device in devicesAt(group.roomId)" —— 遍历当前分组里的设备(设备池 or 选中的房间):key="device.id" —— Vue 必须要有唯一 key:device="device" —— 把当前循环的设备对象传给 DeviceCard.props.device:rooms="sampleRooms" —— 把所有可选房间传给子组件(select 要渲染 option):busy="saving" —— 父组件的 saving 状态传给子组件,禁用 select 和保存按钮@move="moveSampleDevice" —— 监听子组件 emit('move', {...}) 事件,触发父组件的 moveSampleDevice 函数这是"父调用"模式的完整链路:DeviceCard emit('move', {id, roomId}) → App.vue 的 moveSampleDevice({id, roomId}) → runAction 包装 → 你填的函数体。
async function moveSampleDevice({ id, roomId }) { await runAction(async () => { // BEGIN W04-V3 const moved = await moveSampleDeviceTo(id, roomId) sampleDevices.value = listSampleDevices() // 构造目的地名字:null → 设备池;否则用 sampleRooms 找名字 const destination = sampleRooms.find(r => r.id === moved.roomId)?.name ?? '设备池' message.value = `"${moved.name}"已移到${destination}。` // END W04-V3 }) }
四个 BEGIN/END 都填完后,打开 web04/src/App.vue 对照。脚手架相同,你只改了 4 处标记块。
| 标记块 | 核心动作 | web04 关键代码 |
|---|---|---|
W04-V1-RENAME | 调 PATCH renameRoom → loadRooms(renamed.id) | App.vue L48-52 |
W04-V1-DELETE | 调 DELETE deleteRoom → selectedId 处理 → loadRooms(nextId) | App.vue L55-60 |
W04-V2(模板) | DeviceCard v-for + :props + @move | App.vue L117-120 |
W04-V3 | moveSampleDeviceTo → 刷新数组 → 构造 destination → 消息 | App.vue L64-69 |
| DeviceCard.vue | defineProps / defineEmits / watch / emit('move') | src/components/DeviceCard.vue L1-11 |
| deviceSamples.js | moveSampleDeviceTo 改内存 roomId 字段 | src/deviceSamples.js L16-22 |
| 知识点 | 一句话解释 |
|---|---|
| PATCH 方法 | RESTful 中"部分更新",只传要改的字段(如 { name }) |
| DELETE 方法 | 删除资源,后端通常返回 null 或空 |
| 路径参数 | /api/rooms/${encodeURIComponent(id)} —— RESTful 用路径区分不同资源 |
| 子组件 | components/*.vue 可以 import DeviceCard from ... 当标签用 |
| defineProps | 子组件声明"我要收哪些参数" |
| defineEmits | 子组件声明"我要发哪些事件" |
| watch props | props 只读,所以镜像到本地 ref;watch 让外部 prop 变化时本地 ref 同步 |
| null vs '' | HTML select 空值是 '';接口约定 null 表示"无 roomId"(移回设备池) |
| split 两套数据源 | apiRooms 全真实后端;sampleDevices 独立示例(roomSamples 删除) |
| request(path) | 从 web03 的 request({}) 固定路径,升级成真正可复用的 fetch 封装 |
四个标记块填完后,试试下面几个改进: