【问题标题】:Compute data from an array with VueJS使用 VueJS 从数组中计算数据
【发布时间】:2018-05-01 16:53:24
【问题描述】:

我想用 vueJS 从我的 json 中计算数据

数据是这样的

来自我的 api 的 json

[
    {
        "id": 4,
        "votes": 0
    },
    {
        "id": 3,
        "votes": 1
    },
]

为了获取和渲染这些数据,我使用了这个 vueJS 文件

app.js

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});

现在我想创建一个 vue 变量来显示我的 index.html 中的总票数

index.html

<div v-for="result in results">
    <p>Votes {{ result.votes }}.</p>
    <p>Id : {{ result.id }}</p>
</div>
<div>
    <p>Total of votes : {{ resultsVotes }}</p>
</div>

【问题讨论】:

  • 问题是……?如何计算resultsVotes
  • 我想“我想用 vueJS 从我的 json 计算数据”和“现在我想创建一个 vue 变量来显示我的 index.html 中的总票数”非常简单......

标签: javascript json vue.js


【解决方案1】:

如果问题是如何计算resultVotes,推荐computed值:

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  computed: {
    resultVotes () {
      return this.results.reduce((sum, val) => sum + val.votes, 0);
    }
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});

【讨论】:

  • 有了这个我得到了this.resultsVotes = this.results.reduce((sum, curr) =&gt; sum + curr.votes, 0);
【解决方案2】:

您可以在then 函数中只对reduce 投票的总和

axios.get("http://example.com/votes.json")
    .then(response => {
         this.results = response.data;
         this.resultsVotes = this.results.reduce((sum, curr) => sum + curr.votes, 0);
    });

【讨论】:

  • 此代码显示总数但出现此错误Error in render: "TypeError: Cannot read property 'id' of undefined"
  • 我的代码中没有使用id 属性。问题出在别的地方
  • 需要使用parseFloat(curr.votes)来防止字符串类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 2019-06-13
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
相关资源
最近更新 更多