列表渲染
计算属性实现computed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>江河三千里</title>
<script type="text/javascript" src="http://ljy0427.online/js/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" placeholder="筛选条件" v-model="keyWord">
<ul>
<li v-for="(item,index) in filFrus" :key="index">
{{item.name}}:{{item.price}}
</li>
</ul>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
var vm=new Vue({
el:'#app',
data:{
keyWord:"",
fruits:[
{id:001,name:"苹果",price:"1.01"},
{id:002,name:"草莓",price:"2.02"},
{id:003,name:"猕猴桃",price:"4.01"},
{id:004,name:"樱桃",price:"1.01"},
{id:005,name:"蓝莓",price:"1.01"}
]
},
computed:{
filFrus(){
return this.fruits.filter((val)=>{
return val.name.indexOf(this.keyWord)!==-1;
})
}
},
methods:{}
});
</script>
</html>
监听属性实现watch
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>江河三千里</title>
<script type="text/javascript" src="http://ljy0427.online/js/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" placeholder="筛选条件" v-model="keyWord">
<ul>
<li v-for="(item,index) in others" :key="index">
{{item.name}}:{{item.price}}
</li>
</ul>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
var vm=new Vue({
el:'#app',
data:{
keyWord:"",
fruits:[
{id:001,name:"苹果",price:"1.01"},
{id:002,name:"草莓",price:"2.02"},
{id:003,name:"猕猴桃",price:"4.01"},
{id:004,name:"樱桃",price:"1.01"},
{id:005,name:"蓝莓",price:"1.01"}
],
others:[]
},
watch: {
keyWord:{
immediate:true,
handler(oldValue,newValue){
this.others=this.fruits.filter((val)=>{
return val.name.indexOf(this.keyWord)!==-1;
})
}
}
},
methods:{}
});
</script>
</html>
</html>
可以发现,同一种功能中,虽然watch和computed都能实现,但是在computed中所用到的代码量更少,因此,若两者都能实现的功能,尽量使用computed。