【问题标题】:Vue.js re-sort after input valueVue.js 在输入值后重新排序
【发布时间】:2021-07-18 17:20:56
【问题描述】:

我有一个按计算属性(按价格)排序的 html 表格。

我的 HTML:

<input v-model="inputNumber" type="number">
<table>
                <thead>
                  <tr>
                    <th>Fruit</th>
                    <th>Price</th>
                    <th>Final price</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="fruit in orderFruits">
                    <td>{{ fruit.name }}</td>
                    <td>{{ fruit.price }}</td>
                    <td v-if="!input">{{ fruit.price }}</td>
                    <td v-else>{{ fruit.price * inputNumber }}</td>
                  </tr>
                </tbody>
</table>

我的 JS:

let app = new Vue({
  el: "#app",

  data: {
    fruits: [{"name": "apple", "price": 5}, {"name": "banana", "price": 6},{"name": "orange", "price": 7}],
    inputNumber: null
  },

  computed: {
    orderFruits: function () {
      function compare(a, b) {
        return (a.price - b.price);
      }
      return this.fruits.slice().sort(compare);
    },
...

输入值后如何重新排序列表?

提前谢谢你!

【问题讨论】:

    标签: javascript arrays vue.js sorting vuejs2


    【解决方案1】:

    您的比较器应考虑inputNumber,以便对该属性的更改会自动重新计算orderFruits。还要确保使用arrow functioncompare() 来捕获其中的组件上下文:

    {
      computed: {
        orderFruits: function () {
          const compare = (a, b) => {
            return this.inputNumber
              ? (a.price * this.inputNumber - b.price * this.inputNumber)
              : (a.price - b.price);
          }
          return this.fruits.slice().sort(compare);
        },
      }
    }
    

    demo

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 2021-12-27
      • 2023-03-04
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多