11-3.Vue2.x基本列表—列表排序—sort

列表排序—sort(改变原数组)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>列表排序</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>
  <body>
    <!-- 
        想要对数据进行加工后再展示且不想破坏原数据,最好用computed计算属性
     -->
    <!-- 准备一个容器 -->
    <div id="root">
      <h2>人员列表</h2>
      <input v-model="keyWord" type="text" placeholder="请输入姓名" />
      <button @click="sortType = 1">年龄升序↑</button>
      <button @click="sortType = 2">年龄降序↓</button>
      <button @click="sortType = 0">原顺序</button>
      <ul>
        <li v-for="(p,index) in fmtPersons">
          {{p.name}}---{{p.sex}}---{{p.age}}岁
        </li>
      </ul>
    </div>

    <script>
      new Vue({
        el: "#root",
        data: {
          keyWord: "",
          sortType: 0, // 0原顺序  1升序   2降序
          persons: [
            { id: "001", name: "马冬梅", age: 20, sex: "男" },
            { id: "002", name: "周冬雨", age: 29, sex: "女" },
            { id: "003", name: "周杰伦", age: 32, sex: "男" },
            { id: "004", name: "温兆伦", age: 50, sex: "女" },
          ],
        },
        // 使用computed优势,列表过滤不影响
        // 计算属性(keyWord变时,调用fmtPersons)
        computed: {
          fmtPersons() {
            const { persons, keyWord, sortType } = this;
            // 1.根据关键词过滤
            let arr = persons.filter((p) => p.name.indexOf(keyWord) !== -1);
            // 2.如果需要排序(sort影响原数组)
            if (sortType) {
              // 排序
              arr.sort((a, b) => {
                if (sortType === 1) return a.age - b.age;
                else return b.age - a.age;
              });
            }
            // 3.返回结果
            return arr;
          },
        },
        methods: {
          demo() {
            console.log(1);
          },
        },
      });
    </script>
  </body>
</html>

相关推荐

  1. 11-3.Vue2.x基本列表列表排序sort

    2024-04-22 13:58:06       41 阅读
  2. 11-4.Vue2.x基本列表列表更新—push

    2024-04-22 13:58:06       33 阅读
  3. 11-2.Vue2.x基本列表列表过滤 filter--computed

    2024-04-22 13:58:06       39 阅读
  4. Vue2学习笔记(列表渲染)

    2024-04-22 13:58:06       51 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-22 13:58:06       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-22 13:58:06       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-22 13:58:06       87 阅读
  4. Python语言-面向对象

    2024-04-22 13:58:06       96 阅读

热门阅读

  1. spring注解整理

    2024-04-22 13:58:06       31 阅读
  2. Qt 实战(1)Qt 概述

    2024-04-22 13:58:06       195 阅读
  3. Qt——选中所有的RadioButton

    2024-04-22 13:58:06       76 阅读
  4. 设计模式-策略模式

    2024-04-22 13:58:06       36 阅读
  5. 舵机的使用

    2024-04-22 13:58:06       38 阅读
  6. 给c++小白的教程7:保留小数输出

    2024-04-22 13:58:06       37 阅读
  7. Android startForegroundService与startForeground

    2024-04-22 13:58:06       37 阅读