Javascript 使用VueJS从阵列计算数据

Javascript 使用VueJS从阵列计算数据,javascript,json,vue.js,Javascript,Json,Vue.js,我想用vueJS从json计算数据 数据是这样的 来自我的api的json [ { "id": 4, "votes": 0 }, { "id": 3, "votes": 1 }, ] 要获取和呈现此数据,我将使用此vueJS文件 app.js const vm = new Vue({ el: '#app', data: { results: [] }, mounted() {

我想用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>

投票{{结果.投票}

Id:{{result.Id}

投票总数:{{resultsVotes}


您只需
功能中减少
投票总数,然后
即可

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

如果问题是如何计算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})
  },
});

问题是。。。?如何计算
resultsvolds
?我认为“我想用vueJS从我的json计算数据”&“现在我想创建一个vue变量来显示index.html中的投票总数”非常简单…通过这个我得到了
this.resultsvolds=this.results.reduce((sum,curr)=>sum+curr.vows,0)此代码显示总数,但在渲染中出现此错误:“TypeError:无法读取未定义的属性“id”
我的代码中没有使用
id
属性。问题在另一个地方,需要使用
parseFloat(curr.vots)
来防止字符串类型。