因为公司断网了,看到了filter随手写了一下,因为没有太多技术含量,考虑了一下要不要放上来,但是想到我刚入门的时候就一直想找到这种不是很深奥,中规中矩的代码,所以写了下来,给刚入行的朋友参考
<div>
<input type="text" v-model="search">
<span class="xiugia" @click="xiugiaClick">搜索</span>
<!-- 被搜索的数据 -->
<div style="display: none">
<div v-for="(item, index) in dataarr" :key="index">{{item.ceshi}}</div>
</div>
<!-- 搜索结果展示 -->
<div v-if="dataarrElse.length>0">
<div v-for="(item, index) in dataarrElse" :key="index">{{item.ceshi}}</div>
</div>
<!-- 搜索的内容在数据库中不存在时给的一种提示 -->
<div v-else>抱歉,您搜索的内容不存在</div>
</div>
data () {
return {
search: '',
dataarr: [
{ceshi: 'VUE', id: '1'},
{ceshi: 'CSS', id: '2'},
{ceshi: 'Java', id: '3'},
{ceshi: '香蕉', id: '3'},
{ceshi: '哈', id: '3'},
{ceshi: '哈哈', id: '3'},
{ceshi: '苹果', id: '3'},
{ceshi: '橘子', id: '3'},
{ceshi: '芒果', id: '3'},
{ceshi: '芒', id: '3'},
{ceshi: '橙子', id: '3'},
{ceshi: '荔枝', id: '3'},
{ceshi: 'VUE1', id: '1'},
{ceshi: 'VUE2', id: '1'}
],
dataarrElse: []
}
},
methods: {
xiugiaClick () {
// 清空上次搜索的内容
this.dataarrElse.length = 0
this.dataarr.filter((item, index) => {
if (item.ceshi.indexOf(this.search) !== -1) {
this.dataarrElse.push(item)
}
})
// 清空搜索框
this.search = ''
}
}
参考文献:vue官网 https://cn.vuejs.org/v2/guide/