Vue.js练习-搜索页面的实现
2019-03-13 本文已影响0人
朱芮林
<div id="app">
<div class="container">
<span>
<input type="text" v-model="searchString" placeholder="请输入搜索内容" class="input-box" />
<input type="button" class="btn" @click="handleSearch" value="百度一下"/>
//实现按钮的搜索功能
</span>
<br>
<br>
<div class="item" v-for="article in articles_array">
<a :href="article.url" class="item-title">
{{article.title}}
</a>
<div class="item-thumbnail">
<a :href="article.url" class="item-title">
<img :src="article.image">
</a>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// 实例化一个Vue对象
var app = new Vue({
el: '#app',
data: {
searchString: "",
// 数据模型
articles: [{
"title": "堪称神器的3款在线工具,你一定用得上!",
"url": "https://www.jianshu.com/p/e83e7999346b",
"image": "https://img.haomeiwen.com/i11438996/56b25f32c9307b4b?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp"
},
{
"title": "经典面试题:从 URL 输入到页面展现到底发生什么?",
"url": "https://www.jianshu.com/p/45ba3e0d0c7e",
"image": "https://img.haomeiwen.com/i3973862/d90954249a6f6ccd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp"
},
{
"title": "如何免翻墙使用谷歌搜索和Chrome应用商店",
"url": "https://www.jianshu.com/p/484f8e6c88f6",
"image": "https://img.haomeiwen.com/i858154/015a4b083685a3d1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/800/format/webp"
},
{
"title": "四款前所未有好用的黑科技APP,绝对的良心实用,赶紧告诉家人",
"url": "https://www.jianshu.com/p/2aec84d269fe",
"image": "https://img.haomeiwen.com/i16042993/168b2cb17fd7ec0c?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp"
},
{
"title": "坚持学英语的方法有哪些",
"url": "https://www.jianshu.com/p/0a6a61b0933c",
"image": "https://img.haomeiwen.com/i3525704/c7293758fc59e56b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/960/format/webp"
}
],
articles_array: [] //该变量用来存放搜索结果
},
created: function() {
this.articles_array = this.articles; //初始化加载页面的时候,先存放全部数据
},
methods: {
handleSearch: function() {
var searchString = this.searchString;
var len = this.articles.length;
if (!searchString) {
this.articles_array = this.articles;//关键词为空,返回全部数据
}
searchString = searchString.trim().toLowerCase();
this.articles_array = this.articles_array.filter(function(item) {
if (item.title.toLowerCase().indexOf(searchString) != -1) {
return item;
}
})
}
}
再加上相关样式
结果如图:
结果.png