Vue.js:将Promise结果添加到Array

时间:2018-01-19 12:25:13

标签: arrays vue.js promise vuejs2 javascript-objects

我有以下Vue.js组件:

<template>
  <div>
    <pre>{{ $data }}</pre>
  </div>
</template>

<script>
  import { getPrice, getPriceForTimestamp } from '../api/crypto';
  import { cryptostorage } from '../api/utils';

  export default {
    name: 'test',
    data () {
      return {
        cryptoLocalStorage: cryptostorage.fetch()
      }
    },
    methods: {
      getPriceForAmount() {
        for (let i = 0; i < this.cryptoLocalStorage.length; i++) {
          let cryptoName = this.cryptoLocalStorage[i].title;
          let cryptoDate = this.cryptoLocalStorage[i].date;
          let cryptoAmount = this.cryptoLocalStorage[i].amount;

          let historicPrice = getPriceForTimestamp(cryptoName, cryptoDate);
          Promise.all([historicPrice]).then((values) => {
            this.cryptoLocalStorage[i].purchaseDatePrice = values[0];
            this.cryptoLocalStorage.push({ purchaseDatePrice: values});
          }).catch(e => console.error(e));
        }
      }
    },
    created() {
        this.getPriceForAmount();
    }
  }
</script>

这是$data给我的回复:

{
  "cryptoLocalStorage": [
    {
      "id": 0,
      "title": "ETH",
      "amount": "0.5",
      "date": "2018-01-16T12:39:00.000Z",
      "purchaseDatePrice": 1050.26
    },
    {
      "id": 1,
      "title": "BTC",
      "amount": "1",
      "date": "2018-01-09T12:42:00.000Z",
      "purchaseDatePrice": 14468.5
    },
    {
      "id": 2,
      "title": "LTC",
      "amount": "0.003",
      "date": "2017-11-14T12:48:00.000Z",
      "purchaseDatePrice": 62.13
    },
    {
      "purchaseDatePrice": [
        14468.5
      ]
    },
    {
      "purchaseDatePrice": [
        1050.26
      ]
    },
    {
      "purchaseDatePrice": [
        62.13
      ]
    }
  ]
}

问题是我现在purchaseDatePrice重复了,只需要在ID,标题等对象中也是如此。

  

this.cryptoLocalStorage.push({purchaseDatePrice:values});

导致问题,但如果我将其删除,则this.cryptoLocalStorage[i].purchaseDatePrice = values[0];不再有效。

我还尝试将this.cryptoLocalStorage[i].push({ purchaseDatePrice: values});与索引一起使用,但会导致错误TypeError: _this2.cryptoLocalStorage[i].push is not a function

1 个答案:

答案 0 :(得分:1)

Vue.set(this.cryptoLocalStorage[i], 'purchaseDatePrice', values[0])而不是

this.cryptoLocalStorage[i].purchaseDatePrice = values[0];

如果purchaseDatePrice属性不存在于单个数组项的初始模型中,则不能仅向该项添加新属性。 I bet that THIS will explain nature of your problem