You need to enable JavaScript to run this app. 使用Axios与Vue Bootstrap表格展示API数据时报products未定义错误
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios与Vue Bootstrap表格展示API数据时报products未定义错误

代码问题定位与修复

触发报错的核心原因和附带的其他问题逐行列明:

  • 子组件Props拼写不匹配(直接触发报错)
    父组件传值的key是products,但PagTable组件的props声明把单词拼错成了proudcuts,导致子组件完全接收不到父组件传入的列表数据,模板中直接引用products做循环渲染时,就会触发“属性未定义”的报错。
  • data定义与方法内引用大小写不一致
    App.vue的data里把分页变量写成了大写开头的Page:1,但请求拼接地址时引用的是小写的this.page,JS严格区分大小写,这里实际取值会是undefined,就算props问题修好,也会因为请求地址拼接错误拿不到接口数据。
  • axios错误注册
    代码里的Vue.use(axios)属于无效写法,axios是独立的HTTP请求库,不是符合Vue插件规范的对象,不能通过Vue.use全局注册。当前代码因为是在局部直接导入axios调用,暂时不会因为这行直接报错,但属于冗余错误代码,可以直接删掉。
  • 模板逻辑冗余
    PagTable组件的循环行里,序号部分写死了数字1,又用products.indexOf(product) + 1计算序号,会导致显示混乱;另外图片判断的product.image.url没有做空值兜底,如果image字段不存在会直接抛空指针错误。

修正后的代码参考

App.vue

<template>
  <div id="app" class="container">
    <PagTable :products="products"/>
  </div>
</template>

<script>
import axios from 'axios'
import PagTable from './components/PagTable.vue'

const vshredAPI = 'https://app.vshred.com/api/offers?include=images&per_page=25&page='

export default {
  name: "app",
  components: {
    PagTable
  },
  data(){
    return {
      // 统一小写命名,和方法内引用保持一致
      page: 1,
      products: []
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    fetchData () {
      axios.get(vshredAPI + this.page)
        .then(({data}) => {
          // 如果接口返回结构是多层嵌套,比如列表存在data.data字段,这里要对应调整取值路径
          this.products = data
        })
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

PagTable.vue

<template>
  <table class="table">
    <thead class="thead-dark">
      <tr>
        <th scope="col">id</th>
        <th scope="col">Name</th>
        <th scope="col">Image</th>
        <th scope="col">Price</th>
        <th scope="col">Purchase</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(product, index) in products" :key="product.id">
        <!-- 直接用循环索引计算序号,去掉冗余的硬编码1 -->
        <th scope="row">{{ index + 1 }}</th>
        <td>{{product.id}}</td>
        <td>{{product.name}}</td>
        <td>
          <!-- 加可选链做空值兜底,避免image字段不存在时报错 -->
          <img v-if="product.image?.url" class="image" :src="product.image.url"/>
        </td>
      </tr>
    </tbody>
  </table>  
</template>

<script>
export default {
  name: 'PagTable',
  // 修正props拼写,加上默认值兜底,避免父组件传值为空时报错
  props: {
    products: {
      type: Array,
      default: () => []
    }
  }
}
</script>
<style scoped>
</style>

内容的提问来源于stack exchange,提问作者Justin Boyde

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 13:06:04