Activity 4: Find author by name
1. Understanding the Goal
在 authors 数组中查找 name 等于目标字符串(例如 "George Orwell")的作者对象,并使用 Vue 的 computed 保持结果为响应式。
2. Step-by-Step Instruction
- Step 1: Use the
findmethod to search through theauthorsarray. - Step 2: Inside the
findmethod, match thenameproperty with the target string"George Orwell". - 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.name === 'George Orwell' | 匹配条件:作者的 name 等于 "George Orwell"。 |
const orwell = ... | 将计算结果赋给 orwell;在模板中可直接使用(自动解包),在脚本中访问原始值需使用 orwell.value。 |