Vue调用CoinGecko接口访问secret-finance属性报错如何解决
问题原因
- axios 发起请求后返回的完整响应对象中,接口返回的业务数据存储在
data属性下,直接从response根对象读取字段无法获取到接口返回的加密货币价格数据。 - 接口返回的字段名
secret-finance包含连字符,JavaScript 语法规定点运算符后只能跟合法的标识符(不能包含连字符),直接写response.secret-finance会被引擎识别为减法运算,直接抛出语法错误。
解决方案
修改取值逻辑,改为通过data属性读取接口返回数据,同时使用方括号语法读取带特殊字符的属性即可,修改后的代码如下:
async getCurrentSefiPrice() { await axios .get( "https://api.coingecko.com/api/v3/simple/price?ids=secret-finance&vs_currencies=usd" ) .then( (response) => (this.sefi_token_current_price = response.data["secret-finance"].usd) ); console.log(this.sefi_token_current_price); }
内容的提问来源于stack exchange,提问作者Haseeb Saeed
相关产品推荐
相关产品推荐

