我正在嘗試使用 primeblocks 組件,我需要將 dataTable 系結到我的 api 的回應
這就是我卡住的地方:當我 console.log(productData) 我得到一個陣列,其中包含來自我的 api 而不是常規陣列的所有產品的陣列
<template>
<div>
<DataTable :value="productData" responsiveLayout="scroll">
<Column field="SKU" header="Code"></Column>
<Column field="name" header="Name"></Column>
<Column field="brand" header="Brand"></Column>
<Column field="color" header="Color"></Column>
</DataTable>
</div>
</template>
<script>
import axios from 'axios';
let productData = [];
export default {
data() {
return {
productData: null
}
},
mounted() {
const loadProducts = async () => {
const response = await axios.get("http://localhost:1337/products")
productData.value = response.data.products;
};
loadProducts()
}
}
console.log(productData)
</script>
這是我的 console.log
[]
value: (87) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
length: 0
[[Prototype]]: Array(0)
我顯然做錯了什么,如果有人能指出我正確的方向,那就太棒了
uj5u.com熱心網友回復:
您正在組件外部登錄(當組件被決議時)。在 await 之后,您可能希望在loadProducts函式內部進行控制臺response。
另一個問題是productData沒有反應。
您可能想使用:this.productData = response.data.products.
您不需要外部 productData (至少在您目前所展示的內容中)。
以下是我使用 Options API 撰寫組件的方式:
<template>
<DataTable :value="products" responsiveLayout="scroll">
<Column v-for="col in columns"
:key="col.field"
v-bind="col" />
</DataTable>
</template>
<script>
import axios from 'axios';
export default {
data: () => ({
products: [],
columns: [
{ field: 'SKU', header: 'Code' },
{ field: 'name', header: 'Name' },
{ field: 'brand', header: 'Brand' },
{ field: 'color', header: 'Color' }
]
}),
methods: {
loadProducts() {
axios.get("http://localhost:1337/products")
.then(({ data }) => this.products = data?.products || [])
}
}
mounted() {
this.loadProducts()
}
}
</script>
uj5u.com熱心網友回復:
我不太明白你為什么要使用loadProducts,因為它也可以使用.then關鍵字來解決(IMO 看起來更簡潔,而且也是異步執行的):
axios.get("http://localhost:1337/products").then(res=>{
this.productData = res.data.products;
})
此外,如果可能,不要使用null,而是[]在 vue/nuxt 中宣告資料屬性時使用。
干杯!
uj5u.com熱心網友回復:
它應該是
productData.push(...response.data.products)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504883.html
標籤:javascript Vue.js Vuejs3 主播
上一篇:在ReactJS中更新陣列
下一篇:百分比變化計算器無法多次作業
