尝试使用Axios和Vue引导表显示API中的数据

问题描述

大家好,所以我无法从此API向我的Vue引导表显示数据。

这给了我这个错误属性方法“产品”未在实例上定义,而是在渲染过程中被引用。通过初始化属性,确保该属性在数据选项中或对于基于类的组件都是反应性的。

问题出在我的App.vue中,我在实例上定义了产品。所以我不明白为什么它会引发这个错误

这是我的App.vue

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

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

const vshredAPI = 'https://app.vshred.com/apI/Offers?include=images&per_page=25&page=1'

Vue.use(axios)
export default {
        name:"app",components: {
            PagTable
        },data(){
            return {
                Page:1,products: []
            }
        },mounted() {
            this.fetchData()
        },methods: {
            fetchData () {
                axios.get(vshredAPI + this.page)
                    .then(({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组件

  <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 in products" :key="product.id">
        <th scope="row">1
                    {{ products.indexOf(product) + 1 }}
                </th>
        <td>{{product.id}}</td>
        <td>{{product.name}}</td>
        <td>
                    <img v-if="product.image.url" class="image" :src="product.image.url"/>
                </td>
      </tr>
    </tbody>
  </table>  
</template>

<script>
export default {
    name: 'PageTable',props: {
        proudcuts: Array
    }
}

</script>
<style scoped>
</style>

如果有人能帮助我或指导我,那将非常感谢

解决方法

您的PagTable组件内部有一个错字写为骄傲的刻痕,当它应该是产品时,另一件事与您的v有关,因为如果您这样做,那会很好:

<tbody>
  <tr v-for="(product,index) in products" :key="product.id">
    <th scope="row">
      {{ index + 1 }}
    </th>
    <td>{{product.id}}</td>
    <td>{{product.name}}</td>
    <td>
      <img v-if="product.image.url" class="image" :src="product.image.url"/>
    </td>
  </tr>
</tbody>

如您所见,您可以从v-for获取index属性而不是使用products对象,有关更多信息,请检查链接中的文档:https://br.vuejs.org/v2/guide/list.html