<input type="text" v-model="keyword" placeholder="请输入关键词" />
<hr />
<!-- <button @click="sortBy='asc'">升序</button>
<button @click="sortBy='desc'">降序</button>
<button @click="sortBy='random'">随机</button> -->
<ul>
<li
v-for="item in showList"
v-html="highLight(item.name)+',年龄:'+item.age"
></li>
</ul>
data() {
return {
keyword: "",
sortBy: "asc", // asc升序 desc降序 random随机
people: [
{
id: 1,
name: "旗木卡卡西",
age: 27,
chk: false,
},
{
id: 2,
age: 20,
name: "宇智波鼬",
chk: true,
},
{
id: 3,
name: "宇智波佐助",
age: 16,
chk: true,
},
{
id: 4,
name: "团藏",
age: 38,
chk: false,
},
],
};
},
computed: {
showList() {
const filtedList = this.people.filter(
(item) => item.name.indexOf(this.keyword) > -1
);
switch (this.sortBy) {
case "asc":
return filtedList.sort((a, b) => a.age - b.age);
case "desc":
return filtedList.sort((a, b) => b.age - a.age);
case "random":
return filtedList.sort(() => Math.random() - 0.5);
default:
return filtedList;
}
},
},
methods: {
// 对关键词做高亮处理,为关键字使用span标签包括
highLight(txt) {
return this.keyword
? txt.replace(this.keyword, `<span>${this.keyword}</span>`)
: txt;
},
},