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。

 

 

Logo

前往低代码交流专区

更多推荐