添加JavaScript逻辑
在这一步中,你将把JavaScript逻辑添加到 index.html
文件中。
在 <script>
标签内,添加以下代码:
class Post {
constructor(title, link, img) {
this.title = title;
this.link = link;
this.img = img;
}
}
const app = new Vue({
el: "#app",
data: {
search: "",
postList: [
new Post("小猫", "https://unsplash.com/s/photos/cat", "./images/cat.png"),
new Post("小狗", "https://unsplash.com/@joeyc", "./images/dog.png"),
new Post(
"北极熊",
"https://unsplash.com/@hansjurgen007",
"./images/bar.png"
),
new Post(
"小狮子",
"https://unsplash.com/@hansjurgen007",
"./images/lion.png"
),
new Post(
"小鸟",
"https://unsplash.com/@eugenechystiakov",
"./images/birds.png"
),
new Post(
"狐狸",
"https://unsplash.com/@introspectivedsgn",
"./images/fox.png"
)
]
},
computed: {
filteredList() {
return this.postList.filter((post) => {
return post.title.includes(this.search);
});
}
}
});
这段JavaScript代码定义了一个 Post
类,并创建了一个新的Vue实例,该实例具有处理搜索功能所需的数据和计算属性。
Post
类用于创建具有标题、链接和图像属性的帖子实例。
- Vue实例(
app
)使用以下属性创建:
el
:指定挂载Vue实例的元素。
data
:包含搜索输入的 search
属性和 postList
项的数组。
computed
:定义一个 filteredList
计算属性,该属性根据搜索输入过滤 postList
。