<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="../js/vue@2.7.16.js"></script>
    <title>列表过滤</title>
  </head>

  <body>
    <div id="app">
      <h1>列表过滤</h1>
      <input type="text" v-model="keyword" />
      <button @click="sortType = 2">年龄升序</button>
      <button @click="sortType = 1">年龄降序</button>
      <button @click="sortType = 0">重置</button>

      <ul>
        <li v-for="(item,index) in filterPersion" :key="index">
          {{item.name}}---{{item.age}}---{{item.sex}}
        </li>
      </ul>
    </div>
  </body>

  <script>
    const vm = new Vue({
      el: "#app",
      data: {
        sortType: 0,
        keyword: "",
        list: [
          { id: "001", name: "Bunny-001", age: 19, sex: "男" },
          { id: "002", name: "Bunny-002", age: 16, sex: "男" },
          { id: "003", name: "Bunny-003", age: 20, sex: "女" },
          { id: "004", name: "Bunny-004", age: 18, sex: "男" },
          { id: "005", name: "Bunny-005", age: 19, sex: "女" },
        ],
      },
      computed: {
        filterPersion() {
          let newList = this.list.filter(
            (persion) => persion.name.indexOf(this.keyword) !== -1
          );

          if (this.sortType != 0) {
            newList = newList.sort((a, b) =>
              this.sortType == 2 ? a.age - b.age : b.age - a.age
            );
          }

          return newList;
        },
      },
      methods: {},
    });
  </script>
</html>
