簡體   English   中英

v-select 按“項目文本”排序

[英]v-select sorts by "item-text"

我有一個使用 Vuetify 制作的v-select 如何從大到小對這個 v-select 中的項目名稱進行排序?

<v-select
  v-model="selectedFruits"
  :items="fruits"
  label="Favorite Fruits"
  item-text="text"
  return-object
  multiple
>


    fruits: [ { text: 'x', id: '1'}, 
    { text: 'y', id: '2'}, 
    { text: 'a', id: '5'},
    { text: 'h', id: '4'}],

我使用排序方法但失敗了。

這應該很好用

<template>
  <pre>{{ alphaSortedFruits }}</pre>
</template>

<script>
export default {
  data() {
    return {
      fruits: [
        { text: 'x', id: '1' },
        { text: 'y', id: '2' },
        { text: 'a', id: '5' },
        { text: 'h', id: '4' },
      ],
    }
  },
  computed: {
    alphaSortedFruits() {
      return this.fruits.slice().sort((a, b) => a.text.localeCompare(b.text))
    },
  },
}
</script>

這里是游樂場

實際結果

在此處輸入圖像描述


幾點注意事項:

  • 您不必使用localeCompare ,您也可以使用“常規排序”
  • 我也在使用slice()來復制數組,我假設你不想改變原始數組
  • 請記住slice正在做一個淺拷貝,如果你有一個深度嵌套的 object 你需要使用structuredClone 很棒的是它非常高效並且是原生的,不再需要 lodash。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM