最终功能:
showblogs.vue所有代码:
1.获取数据:将获取到的数据赋给 data()中 blogs 数组,this.blogs = data.body.slice(0, 10);
2.监听用户输入:v-model="search",
3.筛选用户输入的内容,match() 方法可在字符串内检索指定的值
用户输入筛选后的数据赋给data()中 blogs 数组
computed: {
filteredBlogs: function () {
return this.blogs.filter((blog) => {
return blog.title.match(this.search);
})
}
},
4.数据渲染到页面:v-for="b in filteredBlogs",直接v-for渲染用户筛选后的列表,用户没输入则渲染全部列表,
5. 在渲染文章内容部分,只显示文章前100字,加...省略号
<article>
{{b.body | snippet}}
</article>
<template>
<div class="show-blogs">
<h1>博客总览</h1>
<input type="text" v-model="search" placeholder="搜索"/>
<div class="single-blog" v-for="b in filteredBlogs">
<router-link>
<h2 v-rainbow>{{b.title}}</h2>
</router-link>
<article>
{{b.body | snippet}}
</article>
</div>
</div>
</template>
<script>
export default {
name: "showblogs",
data() {
return {
blogs: [],
search: ""
}
},
created() {
this.$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function (data) {
//console.log(data);
//只获取10条信息
this.blogs = data.body.slice(0, 10);
//console.log(this.blogs)
})
},
computed: {
filteredBlogs: function () {
return this.blogs.filter((blog) => {
return blog.title.match(this.search);
})
}
},
filters: {
"snippet":function (value) {
return value.slice(0,100)+"..."
}
},
}
</script>
<style scoped>
.show-blogs{
max-width: 800px;
margin:0 auto;
}
.show-blogs h1{
margin-bottom: 20px;
}
.single-blog{
padding:20px;
margin:20px 0;
box-sizing: border-box;
background: #eee;
border:1px dotted #aaa;
}
.single-blog article{
margin-top: 20px;
}
.show-blogs a{
color: #444;
text-decoration: none;
}
input[type="text"]{
padding:8px;
width: 100%;
box-sizing: border-box;
}
</style>