Activity 5: Find author by ID
1. Understanding the Goal
在 authors 数组中查找 id 等于指定值(例如 2)的作者对象,并使用 Vue 的 computed 保持结果为响应式。
2. Step-by-Step Instruction
- Step 1: Use the
findmethod to search through theauthorsarray. - Step 2: Inside the
findmethod, match theidproperty with the target ID (e.g.,2). - Step 3: Wrap the result in a
computedfunction to make it reactive in Vue.js.
3. Code Explanation
| 部分 | 说明 |
|---|---|
computed(...) | Vue.js 的计算属性:当依赖的 authors 数据变化时会自动重新计算。 |
authors.find(...) | JavaScript 数组的 find 方法:返回第一个满足条件的元素,未找到则返回 undefined。 |
(author) => author.id === 2 | 匹配条件:作者对象的 id 必须严格等于 2(使用 === 做严格相等比较)。 |
const austen = ... | 将查找结果赋给 austen;模板中可直接使用,在脚本中访问原始值需用 austen.value。 |