Sort()不起作用

时间:2018-05-21 21:43:08

标签: sorting vue.js axios

我在使用coinmarketcap api排名数据时遇到sort()问题。使用ajax api调用,sort可以返回具有正确排名的数组。使用axios api调用,如下所示,它没有。

这是我使用axios和vue.js的代码:

let coinMarket = 'https://api.coinmarketcap.com/v2/ticker/?limit=10'
let updateInterval = 60 * 1000;

let newApp = new Vue({
  el: '#coinApp',
  data: {
    // data within an array
    results: []
},
  methods: {
    getCoins: function() {
        axios
            .get(coinMarket)
            .then((resp) => {
              this.results = formatCoins(resp);
            });
    },

    getColor: (num) => {
        return num > 0 ? "color:green;" : "color:red;";
    },
},
    created: function() {
        this.getCoins();
    }
})
setInterval(() => {
        newApp.getCoins();
    },
    updateInterval
);
function formatCoins(res) {
    var coinDataArray = []
    Object.keys(res.data).forEach(function(key) {
        coinDataArray.push(res.data[key])
    })
    coinDataArray.sort(function(a,b) {
        return a.rank > b.rank
    })
    console.log(coinDataArray)
}

我哪里错了?

1 个答案:

答案 0 :(得分:2)

如果您查看由https://api.coinmarketcap.com/v2/ticker/?limit=10回复的数据,您会发现所需的数据位于res.data.data下,而不是res.data

所以在function = formatCoins 中,将res.data替换为res.data.data,然后就可以了。



Vue.config.productionTip = false
let coinMarket = 'https://api.coinmarketcap.com/v2/ticker/?limit=10'
let updateInterval = 60 * 1000;

function formatCoins(res) {
    var coinDataArray = []
    Object.keys(res.data.data).forEach(function(key) {
      
        coinDataArray.push(res.data.data[key])
    })
    coinDataArray.sort(function(a,b) {
        return a.rank - b.rank
    })

    return coinDataArray
}

let newApp = new Vue({
  el: '#coinApp',
  data: {
    // data within an array
    results: []
  },
  methods: {
    getCoins: function() {
        axios
            .get(coinMarket)
            .then((resp) => {
              this.results = formatCoins(resp);
            });
    },

    getColor: (num) => {
        return num > 0 ? "color:green;" : "color:red;";
    },
  },
  created: function() {
      this.getCoins();
  }
})
setInterval(() => {
        newApp.getCoins();
    },
    updateInterval
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="coinApp">
    <div v-for="(record, index) in results" :key="index">
      {{index}} - {{record.name}}: {{record.rank}}
    </div>
</div>
&#13;
&#13;
&#13;