这篇文章主要介绍使用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实现搜索功能的示例”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。