【问题标题】:How to alphabetically sort a list of options in Vue.js / Buefy form?如何按字母顺序对 Vue.js / Buefy 形式的选项列表进行排序?
【发布时间】:2018-11-02 09:50:29
【问题描述】:

目前我使用 Vue.js / Buefy 表单显示每个城市的酒店列表:

 <option
   :value="h['@attributes'].Name"
   v-for="h in cities[form.cities[i].index].Hotels.Hotel"
   :key="cities[form.cities[i].index].Hotels.Hotel.Name"
   v-if="isArray(form.cities[i].index)"
   v-text="h['@attributes'].Name"></option>

我应该添加什么来按字母顺序对它们进行排序?我不知所措,因为我不太了解 Vue / Buefy,而且我正在修改其他人编写的代码。

谢谢!

【问题讨论】:

    标签: vue.js vuejs2 buefy


    【解决方案1】:

    了解您的代码在做什么很重要,这样您就知道需要在哪里进行更改。 您的循环 v-for 正在遍历您的数组 cities[form.cities[i].index].Hotels.Hotel(命名对我来说似乎很奇怪)。

    在这个数组中,有一个键 @attributes,它包含一个带有键 Name 的对象,这可能是您想要用于排序的对象。

    通常我会为这些东西使用计算属性,但由于你有基于参数的数组 (form.cities[i].index),我不确定这是否会如此容易。因此,您可以使用一种方法来获取数组的排序版本。在您的 Vue 实例中,将以下内容添加到“方法”属性中:

    methods: {
        sortedHotels: function(hotels) {
            tmp = this.hotels.slice(0);
            tmp.sort(function(a,b) {
                 return (a['@attributes'].Name > b['@attributes'].Name) ? 1 : ((b['@attributes'].Name> a['@attributes'].Name) ? -1 : 0);
            });
            return tmp;
        },
    },
    

    然后,不是循环遍历普通数组,而是循环遍历该数组的函数调用的结果:

     <option
         :value="h['@attributes'].Name"
         v-for="h in sortedHotels(cities[form.cities[i].index].Hotels.Hotel)"
         :key="cities[form.cities[i].index].Hotels.Hotel.Name"
         v-if="isArray(form.cities[i].index)"
         v-text="h['@attributes'].Name"></option>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2014-02-08
      • 2022-01-13
      • 2015-05-04
      相关资源
      最近更新 更多