<template>
<div>
<input type="text" v-model="iName" placeholder="输入名字" />
<button @click="sortType = 2">升序</button>
<button @click="sortType = 1">降序</button>
<button @click="sortType = 0">原序</button>
<ul>
<li v-for="item in filPerson" :key="item.id">
{{ item.id }}--{{ item.name }}--{{ item.age }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
iName: "",
sortType: 0,
persons: [
{ id: "001", name: "马冬梅", age: 11 },
{ id: "002", name: "周冬雨", age: 16 },
{ id: "003", name: "周杰伦", age: 19 },
{ id: "004", name: "温兆伦", age: 12 },
],
// filPerson: [],
};
},
//#region
// 用watch实现
// watch: {
// // iName(val) {
// // this.filPerson = this.persons.filter((p) => {
// // return p.name.includes(val);
// // // return p.name.indexOf(val) != -1;
// // });
// // },
// iName: {
// immediate: true,
// handler(val) {
// this.filPerson = this.persons.filter((p) => {
// return p.name.includes(val);
// });
// },
// },
// },
//#endregion
// 能用computer实现的别用watch,watch可以执行异步操作,comput不可以
// computed 能实现的watch都可以实现,watch可以实现的comput不一定可以实现
computed: {
filPerson() {
// 过滤
const arr = this.persons.filter((p) => {
return p.name.includes(this.iName);
});
// 排序
if (this.sortType) {
arr.sort((a, b) => {
return this.sortType === 1 ? b.age - a.age : a.age - b.age;
});
}
return arr;
},
},
};
</script>
<style>
</style>
网友评论