vue 小案例 获取数据渲染页面 实现文章标题搜索功能

最终功能:

 

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>

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值