【问题标题】:Unable to sort array with lodash and vueJS无法使用 lodash 和 vueJS 对数组进行排序
【发布时间】:2021-02-16 03:03:01
【问题描述】:

我正在尝试建立一个单页网站来展示印度的 covid 病例。基本 url 返回一个按字母顺序排序的数组。我想根据“totalConfirmed”对其进行排序。这是我的代码。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Covid19 India</title>
  <!-- Bootstrap CSS 4.3.1 -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <!-- Axios -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <!-- VueJS -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  
  <!-- Lodash -->
  <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>

</head>
<body>
  <div class="container mt-4" id="app">

    <table class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">Location</th>
          <th scope="col">Total</th>
          <th scope="col">Active</th>
          <th scope="col">Recovered</th>
          <th scope="col">Deaths</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="state, index in states">
          <th scope="row">{{ index + 1 }}</th>
          <td>{{ state.loc }}</td>
          <td>{{ state.totalConfirmed }}</td>
          <td>{{ state.totalConfirmed - (state.discharged + state.deaths)}}</td>
          <td>{{ state.discharged }}</td>
          <td>{{ state.deaths }}</td>
        </tr>
      </tbody>
    </table>
    </table>
  </div>
  
  
  <script>
  const cases = [];
    var app = new Vue({
      el: '#app',
      data: {
        states: []
      },
      mounted: function() {
        axios.get('https://api.rootnet.in/covid19-in/stats/latest')
            .then(response => {
              this.states = response.data.data.regional;
              this.states = cases;
              cases = _.orderBy(cases, 'totalConfirmed', 'desc');
              console.log(cases);
            })
            .catch(error => {
              console.log(error);
            });
      }
          
    })
  </script>
</body>
</html>

在我的控制台中,我收到一个错误“TypeError:_.orderBy 不是函数”。我在这里做错了什么?如果我不使用 orderBy,我的代码运行良好,没有错误。

【问题讨论】:

标签: javascript arrays vue.js sorting lodash


【解决方案1】:

尝试添加 lodash 库。

const _ = require('lodash');     
cases = _.orderBy(cases, ['totalConfirmed']);

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习
  • TypeError: _.orderBy 不是函数
  • 是安装包的问题。试试这个链接的说明npmjs.com/package/lodash.orderbynpm i --save lodash.orderbyvar orderBy = require('lodash.orderby');
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2017-09-08
  • 2022-07-22
  • 2021-07-25
  • 2015-05-10
  • 1970-01-01
相关资源
最近更新 更多