Activity 2: Get Authors Born After 1850
1. Understanding the Goal
我们的目标是得到一个只包含 1850 年之后出生作者的响应式列表。我们将使用 JavaScript 的 filter 方法进行筛选,并用 Vue 的 computed 包裹逻辑,这样当 authors 数据变化时,结果会自动更新。
2. Step-by-Step Instruction
- Step 1: Use the
filtermethod to create a new array of authors who were born after 1850. - Step 2: The
filtermethod will take a callback function that checks if thebirthYearof each author is greater than 1850. - Step 3: Use the
computedfunction from Vue.js to create a reactive value.
3. Code Explanation
| 部分 | 说明 |
|---|---|
computed(...) | Vue.js 提供的 计算属性函数,返回一个响应式的只读值;当依赖的 authors 数据发生变化时,它会自动重新计算。 |
authors.filter(...) | JavaScript 数组的 filter 方法,用于从 authors 中筛选出符合条件的作者。 |
(author) => author.birthYear > 1850 | 筛选条件:作者的 birthYear 大于 1850。只保留符合条件的作者对象。 |
const modernAuthors = ... | 将最终的计算结果赋值给 modernAuthors,这个值会随着 authors 的变化自动更新。 |