<html>
<head>
<script src="http://cdn.bootcss.com/vue/2.1.4/vue.js"></script>
</head>
<body>
<div id="app">
<!--<li v-for="n in even(persons)">{{ n.name }}</li>-->
<li v-for="n in personsView">{{ n.name }} :: {{n.age}}</li>
<input type="text" v-model="age" placeholder="age" />
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
age:0,
persons :[{
name: '张三',
age: 30
}, {
name: '李四',
age: 40
}, {
name: '王五',
age: 10
}],
personsView:[{
name: '张三',
age: 30
}, {
name: '李四',
age: 40
}, {
name: '王五',
age: 10
}]
},
methods: {
even: function(persons) {
return persons.filter(function(p) {
return p.age >= 10;
})
}
},
watch:{
age:function(val,oldVal){
console.log('new: %s, old: %s', val, oldVal);
console.log(this.persons.filter(function(p) {
return p.age >= val;
}).slice());
this.personsView = this.persons.filter(function(p){
return p.age >= val;
}).slice();
}
}
});
</script>
</html>
请问有没有更好的办法
1
LancerComet 2016-12-05 00:07:14 +08:00
```
<html> <head> <meta charset="utf-8"> </head> <body> <div id="app"> <li v-for="n in filteredList">{{ n.name }} :: {{n.age}}</li> <input type="text" v-model="age" placeholder="age" /> </div> <script src="http://cdn.bootcss.com/vue/2.1.4/vue.js"></script> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { age:0, persons :[{ name: '张三', age: 30 }, { name: '李四', age: 40 }, { name: '王五', age: 10 }] }, computed: { filteredList () { return this.persons.filter(item => item.age >= this.age) } } }) </script> </body> </html> ``` |
2
q397064399 OP @LancerComet 多谢,我就说我为什么 ES5 通过 computed 方法总是写得通过不了
原来是 this 出错了, ``` <html> <head> <meta charset="utf-8"> </head> <body> <div id="app"> <li v-for="n in filteredList">{{ n.name }} :: {{n.age}}</li> <input type="text" v-model="age" placeholder="age" /> </div> <script src="http://cdn.bootcss.com/vue/2.1.4/vue.js"></script> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { age:0, persons :[{ name: '张三', age: 30 }, { name: '李四', age: 40 }, { name: '王五', age: 10 }] }, computed: { filteredList:function() { var _this = this; return this.persons.filter(function(item){ console.log(this,_this); // 为后来的人做一个说明,这里用 babel 自动转成 ES5 了,这里 this 指向 window 对象 //_this 才是指向 vue 对象, //万恶的原型继承 以及 函数对象,真 TM 恶心人啊 return item.age >= _this.age }); } } }) </script> </body> </html> ``` |