2017-08-26 75 views
0

我想通過使用Vue js 2創建一個可排序的表。我已經生成了一個表,現在只是想知道如何對此表進行排序。Vue js 2表排序

請參閱下面我的代碼:

 <thead> 
     <tr> 
      <th class="table-header">Metric</th> 
      <th class="table-header" v-for="metric in metricList"><a href="#">{{metric}}</a></th> 
     </tr> 
    </thead> 
    <tbody> 
     <template v-for="item in metricItem"> 
      <tr> 
       <td class="table-cell" style="font-weight:bold"> {{ item }}</td> 
       <template v-for="metric in metricList"> 
        <td class="table-cell"> 
         {{getData[item][metric]}} 
        </td> 
       </template> 
      </tr> 
     </template> 
    </tbody> 

<script> 
import { mapGetters, mapMutations } from 'vuex'; 
export default { 
    name: 'scores', 

    data(){ 
     return { 
      metricList : ["Current", "Min", "Avg", "Max"], 

      metricItem : [ 
       'Happiness Score', 
       'Sadness Score' 
      ] 
     } 
    }, 


    computed: { 
     ...mapGetters ([ 
      'getData', //getter to get data 
     ]) 
    } 
} 
</script> 

和數據集是這樣的:

getData { 

    Happiness Score { 

     Min : 62, 
     Max : 154, 
     Avg : 103 
     Current : 100 

    }, 

    Sadness Score { 

     Min : 66, 
     Max : 54, 
     Avg : 73 
     Current : 45 

    }, 

} 

我試圖通過創建一個排序表Vue公司JS 2.我已經生成一個表,現在只是想知道如何對這個表進行排序。

回答

0

如果要單擊表頭中顯示的度量標準時對錶格進行排序,請添加排序方法並使用@click進行綁定。

// ... 
methods: { 
    sort(metric) { 
    this.metricItem = this.metricItem.sort((item1, item2) => { 
     // change `>=` to `<` if you want to sort in descending order 
     return this.getData[item1][metric] >= this.getData[item2][metric]; 
    }); 
    }, 
} 
// ... 

查看完整演示here

+0

感謝隊友,它工作正常。但是,如果我想在第二次點擊時將其降序,該怎麼辦? –

+0

點擊或標記變量中的順序時,檢查當前訂單。 – choasia