Vue计算属性详解:项目实战搜索排序
<!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>Document</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="test">
<input type="text" v-model="keyword">
<ul>
<li v-for="(item,index) in personsFilter">{{index}} -- {{item.name}} -- {{item.age}}</li>
</ul>
<button @click="sortOrderBy(1)">年龄升序</button>
<button @click="sortOrderBy(2)">年龄降序</button>
<button @click="sortOrderBy(0)">原始顺序</button>
</div>
<script>
new Vue({
el: '#test',
data: {
keyword: '',
orderBy: 0, //0原始,1升序,2降序
persons: [{
name: 'cat',
age: 18
}, {
name: 'fat',
age: 22
}, {
name: 'tom',
age: 16
}, {
name: 'art',
age: 48
}, {
name: 'bot',
age: 18
}, {
name: 'bok',
age: 18
}]
},
computed: {
personsFilter: function() {
var keyword = this.keyword,
orderBy = this.orderBy,
persons = this.persons,
result = null;
result = persons.filter(function(a) {
return a.name.indexOf(keyword) !== -1;
});
if (orderBy !== 0) {
result.sort(function(a, b) {
if (orderBy === 2) {
// b - a 降序
return b.age - a.age
} else {
// a - b 升序
return a.age - b.age
}
})
}
return result;
}
},
methods: {
sortOrderBy(orderBy) {
this.orderBy = orderBy;
}
}
});
</script>
</body>
</html>
有疑问支付宝扫一扫加好友: