首页 > 解决方案 > 在 vue.js 中对表格进行排名并在性能后着色

问题描述

我在 vue js 中对我的数据性能进行排名时遇到问题。到目前为止,我已经制作了以下脚本:

<template>
<div>
    <div class="row">
        <h2> Campaign performance </h2>
        <table class="table table-hover">
            <thead>
                <tr>
                    <th scope="col">Client</th>
                    <th scope="col">Campaign</th>
                    <th scope="col">Impressions</th>
                </tr>
            </thead>
        <tbody>
            <tr v-for="(campaign, name) in campaignPerformance.slice(0,10)" :key="campaign.campaignID">
                 <td>{{campaign.client}}</td>
                 <td>{{campaign.campaign}}</td>
                 <td>{{campaign.impressions}}</td>
            </tr>
        </tbody>
        </table>
    </div>
</div>
</template>
<script>
  import axios from 'axios';
  export default {
   data() {
    return {
    };
   },
  props:['campaignPerformance],
  created() {
  },
};
</script>

现在,这给了我一个包含活动绩效的表格,如下所示: 在此处输入图像描述 但是,我想根据绩效对表格进行排名,并为它着色,如下所示: 在此处输入图像描述 有人可以帮忙吗?

标签: javascripthtmlvue.js

解决方案


首先,让我们处理数字格式。要使用 M(百万)格式化您的数字,请创建一个方法,该方法将输入数字并以百万格式返回值。

formatNumber(labelValue) {
  // Nine Zeroes for Billions
  return Math.abs(Number(labelValue)) >= 1.0e+9

  ? Math.abs(Number(labelValue)) / 1.0e+9 + "B for Billion"
  // Six Zeroes for Millions 
  : Math.abs(Number(labelValue)) >= 1.0e+6

  ? Math.abs(Number(labelValue)) / 1.0e+6 + "M for Million"
  // Three Zeroes for Thousands
  : Math.abs(Number(labelValue)) >= 1.0e+3

  ? Math.abs(Number(labelValue)) / 1.0e+3 + "K for thousands"

  : Math.abs(Number(labelValue));

}

上面的代码是不言自明的。我们接受输入并匹配亿万等的条件。

接下来,我们将继续为我们的表格着色。为此,创建另一个方法并将该方法插入绑定到v-style. 此方法将以 rgba 格式返回颜色,分别为行着色。您可以根据自己的选择设置颜色。

colorRows(value) {
  value--;
  var r,g,b;

  if (value < 4) {
    // green to yellow
    r = Math.floor(255 * (value / 4));
    g = 255;

  } else {
    // yellow to red
    r = 255;
    g = Math.floor(255 * ((4-value%4) / 4));
  }
  b = 0;
  let color = "rgba("+ r + "," + g + "," + b +")"; //Concat rbga for the styled to be binded
  console.log(color);
  return color; 
}

最后,将rowColorandformatNumber方法绑定到 html 并循环数组。

  <tr v-for="(campaign, index) in campaignPerformance" :key="campaign.campaignID">
    <td v-bind:style="{ 'background-color': colorRows(index) }">{{campaign.client}}</td>
    <td v-bind:style="{ 'background-color': colorRows(index) }">{{campaign.campaign}}</td>
    <td v-bind:style="{ 'background-color': colorRows(index) }">
      {{formatNumber(campaign.impressions)}}
    </td>
  </tr>

完整的工作示例:

https://codepen.io/AhmedKhan1/pen/wvGxQOz?editors=1010


推荐阅读