You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Nuxt中使用Axios与AlphaVantage仅获取股票当前价格

提取AlphaVantage接口中的股票当前价格

你只需要从接口返回的对象中逐层提取目标字段即可,具体修改如下:

修改后的代码

模板部分

直接渲染提取到的价格:

<template>
  <div class="bg-gray-900 min-h-screen">
    <p class="text-gray-100 text-xl">
      当前价格: {{ stockPrice }}
    </p>
  </div>
</template>

脚本部分

在asyncData里提取Global Quote下的05. price字段,同时添加简单的异常处理避免报错:

<script>
export default {
  async asyncData ({ $axios }) {
    try {
      const response = await $axios.$get('https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey=****')
      // 提取当前价格字段,用可选链避免结构异常报错
      const stockPrice = response['Global Quote']?.['05. price'] || '暂无数据'
      return { stockPrice }
    } catch (error) {
      console.error('获取股票数据失败:', error)
      return { stockPrice: '获取失败' }
    }
  }
}
</script>

关键说明

  • 接口返回的字段名带空格和序号,必须用方括号语法访问(如response['Global Quote']),无法使用点语法
  • 可选链操作符?.可以防止接口返回不包含Global Quote时出现崩溃
  • 异常处理能在请求失败时给出友好提示

内容的提问来源于stack exchange,提问作者tala hon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 17:35:04