【问题标题】:How to add a custom sort in VueJS?如何在 VueJS 中添加自定义排序?
【发布时间】:2019-11-25 19:17:55
【问题描述】:

我在这里有一个数据结构,我分为标题和项目。我正在尝试应用一个自定义排序,我已经为其创建了一个逻辑方法,但我无法弄清楚如何根据名称和等级单独应用该排序方法。这是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 上的方法分别用于成绩和名称?

【问题讨论】:

    标签: javascript arrays vue.js vuetify.js


    【解决方案1】:

    为了让它发挥作用,我做了一些事情。

    • 定义一个sortKey,您的数据将在此基础上进行排序
    • 单击跨度时将sortKey 作为参数传递
    • 在计算 tableItems 时,使用排序键对数据进行排序

    在下面的代码中查找 cmets

    <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;
        }
    },
    

    你会完成的

    【讨论】:

    • 哇哦。这似乎可行,但是如果我想将其设置为上升和下降怎么办。而不仅仅是一种方式?抱歉,我应该添加这是问题。
    • @Somethingwhatever 我添加了一个编辑部分。如果您需要更多帮助,请告诉我:)
    • 感谢所有帮助。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多