如何在VueJS中添加自定义排序?

时间:2019-11-25 19:17:55

标签: javascript arrays vue.js vuetify.js

我这里有一个数据结构,我将其分为标头和项目。我正在尝试应用自定义排序,我对此没有逻辑,我已经为其创建了一种方法,但是我无法弄清楚如何根据名称和等级分别应用该排序方法。这是指向codepen的链接。

new Vue({
  el: '#app',
  data() {
    return {
      headers: [{
          text: 'Name',
          value: 'Name'
        },
        {
          text: 'Grades',
          value: 'grades'
        },
      ],
      labels: ['Andy', 'Max', 'John', 'Travis', 'Rick'],
      Grades: [99, 72, 66, 84, 91]
    }
  },
  computed: {
    tableItems() {
      let items = [],
        this.labels.forEach((label, i) => {
          let item = {}
          item.name = label
          item.grades = this.Grades[i]
          items.push(item)
          console.log(items)
        })
      return items
    }
  },
  methods: {
    sortBy(prop) {
      this.tableItems.sort((a, b) => a[prop] < b[prop] ? -1 : 1)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />
<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout>
        <v-flex v-for="(header, i) in headers" :key="header.text" xs4 py-1>
          <span>{{ header.text }}
                    <v-icon small @click="sortBy(this.labels)">arrow_upward</v-icon>  
                  </span>
        </v-flex>
        <v-layout v-for="item in tableItems" :key="item.name">
          <v-flex xs4 py-1>
            <span>{{ item.name }}</span>
          </v-flex>
          <v-flex xs4 py-1>
            <span>{{item.grades}}</span>
          </v-flex>

        </v-layout>
      </v-layout>
    </v-container>
  </v-app>
</div>

现在,在保持数据结构和所有方式不变的情况下,如何使v-icon上的方法适用于成绩和姓名?

1 个答案:

答案 0 :(得分:1)

以下是我做过的一些事情,以使其起作用。

  • 定义一个sortKey,您将根据该数据对数据进行排序
  • 单击跨度时将sortKey作为参数传递
  • 计算tableItems时,请使用排序键对数据进行排序

在下面的代码中查找注释

<div id="app">
    <v-app id="inspire">
        <v-container>
        <v-layout>
            <v-flex v-for="header in headers" :key="header.text" xs4 py-1>
            <span>
                {{ header.text }}
                <v-icon small @click="sortBy(header.value)">arrow_upward</v-icon>
                ***** changed the value for name (from Name to name) ****
            </span>
            *** everything else is the same ***
        </v-layout>
        </v-container>
    </v-app>
</div>  

脚本看起来像这样

    <script>
    export default {
      name: "app",
      data() {
        return {
          headers: [
            { text: "Name", value: "name" }, // changed this to name
            { text: "Grades", value: "grades" }
          ],
          labels: ["Andy", "Max", "John", "Travis", "Rick"],
          Grades: [99, 72, 66, 84, 91],
          sortKey: "" // added a sortKey,
        };
      },
      computed: {
        tableItems() {
          let retVal = this.labels.map((label, i) => {
            return {
              name: label,
              grades: this.Grades[i]
            };
          });
          // if there is a sortKey use that
          if (this.sortKey) {
            retVal.sort((a, b) =>
              a[this.sortKey] < b[this.sortKey] ? -1 : 1
            );
          }
          return retVal;
        }
      },
      methods: {
        sortBy(prop) {
          // assign sortKey here, this assignment will retrigger the computation
          this.sortKey = prop;
          console.log(prop);
        }
      }
    };
    </script>

*************编辑******************

为您的排序顺序添加一个方向变量(1升序,-1降序)

所以您的数据看起来像

data() {
    return {
        headers: [
            { text: "Name", value: "name" }, // changed this to name
            { text: "Grades", value: "grades" }
        ],
        labels: ["Andy", "Max", "John", "Travis", "Rick"],
        Grades: [99, 72, 66, 84, 91],
        sortKey: "" // added a sortKey,
        direction: 1 // for ascending order
    };
},

现在在您的程序中,如果您单击相同的内容,则需要更改您的升序或降序状态,请按照您的方法进行操作

methods: {
    sortBy(prop) {
        // if the sortKey was prop to begin with
        if (this.sortKey === prop) {
            this.direction *= -1 // change direction to -ve or positive
        }
        // assign sortKey here, this assignment will retrigger the computation
        this.sortKey = prop;
        console.log(prop);
    }
}

最后,在排序时使用您的方向

computed: {
    tableItems() {
        let retVal = this.labels.map((label, i) => {
            return {
                name: label,
                grades: this.Grades[i]
            };
        });
        // if there is a sortKey use that
        if (this.sortKey) {
            retVal.sort((a, b) =>
                this.direction * // here multiply by the direction
                (a[this.sortKey] < b[this.sortKey] ? -1 : 1)
            );
        }
        return retVal;
    }
},

然后您会完成