这是来自MySQL 8的JSON内容。

MySQL字段“ ticket_json”是JSON类型

[{
    "id": 1,
    "ticket_json": [{
        "id": 1570801381559,
        "qty": 2,
        "name": "Cognac",
        "price": 1000
    }, {
        "id": 1570801382391,
        "qty": 1,
        "name": "Jäger Bomb",
        "price": 900
    }, {
        "id": 1570801386549,
        "qty": 1,
        "name": "VodK Ananas",
        "price": 900
    }],
    "created_at": "2019-10-11 15:43:08",
    "updated_at": "2019-10-11 15:43:08"
    }, {
    "id": 2,
    "ticket_json": [{
        "id": 1570830556370,
        "qty": 1,
        "name": "Peace & Love",
        "price": 600
    }, {
        "id": 1570830560279,
        "qty": 1,
        "name": "Tonic",
        "price": 600
    }],
    "created_at": "2019-10-11 23:49:22",
    "updated_at": "2019-10-11 23:49:22"
    }
}]


我检索像方法存储的数据:

getTickets() {
    fetch('/api/path)
    .then((response) => {
        return response.json()
    })
    .then((data) => {
        this.tickets = data;
    })
    .catch((error) => {
        console.log(error);
    })
}


我显示这样的数据:

<div v-for="ticket in tickets">
    {{ totalTicket }}
</div>


“计算”代码:

    computed: {
    totalTicket() {
        var itemsTotal = 0;
        for(var key in this.tickets) {
            var item = this.tickets[key];

            var subitems = item.ticket_json;
            var subItemsTotal = 0;
            for(var key in subitems) {
                var subitem = subitems[key];
                var subItemsTotal = subItemsTotal + ((subitem.la_qtt * subitem.le_tarif)/100);
            };
            var itemsTotal =+ subItemsTotal;
            console.log(itemsTotal);
            return itemsTotal;
        };
    }
},


在循环中,我将显示每个对象的总和(总票数)(数量*价格)

问题,它在所有循环中显示相同的第一个结果

我对Java语言不是很熟悉。如果可以帮助我,谢谢

最佳答案

totalTicket中,您遍历数组的所有元素,然后计算所有元素的总数。

您还定义了两次var key(两个for循环),并且在第二个循环和内部循环中定义了subItemsTotal ouside,在第一个循环和第二个循环内部中定义了itemsTotal ouside。

您必须创建一个采用单个值并计算总数的方法。

HTML

<div v-for="ticket in tickets" :key="ticket.id">
  For Ticket id {{ticket.id}} the Total is {{ totalSingle(ticket) }}</div>
</div>




methods: {
    totalSingle(ticket) {
      var itemsTotal = 0;
      var subitems = ticket.ticket_json;
      var subItemsTotal = 0;
      for (var key in subitems) {
        var subitem = subitems[key];
        subItemsTotal = subItemsTotal + (subitem.qty * subitem.price) / 100;
      }
      itemsTotal += subItemsTotal;
      return itemsTotal;
    }
}

07-24 09:43