1. 程式人生 > >vue實現搜尋功能

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。