Vue.js:将 Promise 结果添加到数组
Posted
技术标签:
【中文标题】Vue.js:将 Promise 结果添加到数组【英文标题】:Vue.js: Add Promise result to Array 【发布时间】:2018-06-28 16:37:55 【问题描述】:我有以下 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】:试试
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
【讨论】:
以上是关于Vue.js:将 Promise 结果添加到数组的主要内容,如果未能解决你的问题,请参考以下文章
Vue.js 是不是具有将持久对象的副本添加到重复数组的内置方法