决不能习惯失败,因为你要知道,身体的疲惫,不是真正的疲惫;精神上的疲惫,才是真的劳累。
本文实例为大家分享了vue实现搜索功能的具体代码,供大家参考,具体内容如下
methods (要有一定的触发条件才能执行,如点击事件)
<template> <div class="safetyInfo"> <input type="text" name="" id="" placeholder="搜索" v-model="search"/> <button @click="btn">搜索</button> <ul v-for="list in searchData"> <li> <span>{{list.name}}</span> <span>{{list.date}}</span> <span>{{list.depart}}</span> </li> </ul> </div> </template> <script> export default { name: 'HelloWorld', data () { return { search:'', searchData: '', products:[ //假数据 {name:"数据1",date:'2018-01-04',depart:'泸化工1'}, {name:"数据2",date:'2018-01-25',depart:'泸化工2'}, {name:"数据3",date:'2018-02-10',depart:'泸化工3'}, {name:"数据4",date:'2018-03-04',depart:'泸化工4'}, {name:"数据5",date:'2018-05-24',depart:'泸化工5'}, {name:"数据6",date:'2018-10-29',depart:'泸化工6'} ] } }, methods:{ btn:function(){ var search = this.search; if (search) { this.searchData = this.products.filter(function(product) { console.log(product) return Object.keys(product).some(function(key) { console.log(key) return String(product[key]).toLowerCase().indexOf(search) > -1 }) }) } } } } </script>
computed (在HTML DOM加载后马上执行的,如赋值):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> </head> <body> <div id="app"> <input v-model='search' /> <ul v-for="item in searchData "> <li>{{item.name}},价格:¥{{item.price}}</li> </ul> </div> <script> var vm = new Vue({ el: '#app', data: { search: '', products: [{ name: '苹果', price: 25, category: "水果" }, { name: '香蕉', price: 15, category: "水果" }, { name: '雪梨', price: 65, category: "水果" }, { name: '宝马', price: 2500, category: "汽车" }, { name: '奔驰', price: 10025, category: "汽车" }, { name: '柑橘', price: 15, category: "水果" }, { name: '奥迪', price: 25, category: "汽车" }] }, computed: { searchData: function() { var search = this.search; if (search) { return this.products.filter(function(product) { return Object.keys(product).some(function(key) { return String(product[key]).toLowerCase().indexOf(search) > -1 }) }) } return this.products; } } }) </script> </body> </html>
注:some()为数组中的每个元素执行一次callback函数,直到它找到一个返回值为可以转化为布尔值true的值,此时some()方法将立刻返回true,否则立刻返回false
by the way:
watch它用于观察Vue实例上的数据变动。对应一个对象,键是观察表达式,值是对应回调。值也可以是方法名,或者是对象,包含选项。
所以他们的执行顺序为:默认加载的时候先computed再watch,不执行methods;等触发某一事件后,则是:先methods再watch。
以上就是vue如何实现搜索功能。我只愿蓬勃生活在此时此刻,无所谓去哪,无所谓见谁,那些我将要去的地方,都是我从未谋面的故乡;那些我将要见的人,都会成为我的朋友。——萧红更多关于vue如何实现搜索功能请关注haodaima.com其它相关文章!