Activity 9: Render Austen’s works (normalize to { title, year })
1. Understanding the Goal
Render a list of Jane Austen’s works from the nested famousWorks field. Support both string and object formats, displaying the title and (optionally) the year.
2. Step-by-Step Instruction
- Step 1: Reuse the
austencomputed from Activity 5 (the author found by ID). - Step 2: Create a computed
austenWorksthat normalizes each work into{ title, year }. - Step 3: In the template, iterate over
austenWorkswithv-for. - Step 4: Bind a unique
:keyand showtitleplusyearif it exists.
3. Code Explanation
| 部分 | 说明 |
|---|---|
computed(...) | 定义计算属性 austenWorks,当 austen 或其作品数据变化时会自动重新计算。 |
austen.value?.famousWorks ?? [] | 可选链 + 空值合并:若 austen 或 famousWorks 不存在则回退为空数组,避免报错。 |
works.map(...) | 将原始作品条目逐个转换为统一结构。 |
typeof w === 'string' ? { title: w, year: undefined } : ... | 类型分支:字符串作品直接转为 { title, year: undefined },对象作品保留其 title 与 year。 |
{ title: w.title, year: w.year } | 对象作品的标准化结果,确保后续渲染字段一致。 |
v-for="(w, idx) in austenWorks" | 遍历标准化后的作品列表进行渲染。 |
:key="w.title + '-' + (w.year ?? idx)" | 复合 key,优先使用 title 与 year,无年份时以索引兜底,保证列表渲染稳定。 |
<span v-if="w.year"> ({{ w.year }})</span> | 条件渲染:仅在存在年份时显示。 |
v-if / v-else | 当 austenWorks 为空时显示“无数据”提示,提升可用性。 |