[英]Undefined data variable Vue.js when using axios
這讓我發瘋。
我將 axios 響應中的值分配給我的 vue 數據,如下所示:
mounted() {
axios
.get('/campaigns/new.json')
.then(response => (
this.kits = response.data[0].kits,
)
)
我可以使用 vue 開發人員工具看到我的 this.kits 有一個包含 8 個項目的數組(正確)
當我之后嘗試使用this.kits
或執行console.log(this.kits)
時,我得到undefined 或 empty array 。
我到底在想什么? 請幫忙。 謝謝
mounted() {
axios
.get('/campaigns/new.json')
.then(response => (
this.kits = response.data[0].kits,
this.kitProducts = response.data[0].kitproducts,
this.products = response.data[0].products,
this.boxes = response.data[0].boxes,
this.categories = response.data[0].categories,
this.extras = response.data[0].extras,
this.isCurrentUser = response.data[0].user,
this.giftpacks = response.data[0].giftpacks
)
)
console.log(this.kits)
console.log(this.kits)
將 output:
您的 console.log 在 promise 請求啟動后立即執行,您必須將其放在then
塊內的末尾,或者如 Nicola 所說,使用 async await
嘗試這個:
async mounted() {
const response = await axios.get('/campaigns/new.json')
this.kits = response.data[0].kits
this.kitProducts = response.data[0].kitproducts
this.products = response.data[0].products
this.boxes = response.data[0].boxes
this.categories = response.data[0].categories
this.extras = response.data[0].extras
this.isCurrentUser = response.data[0].user
this.giftpacks = response.data[0].giftpacks
console.log(this.kits)
}
嘗試等待您的數據。 將 API 調用移至方法:
methods: {
getData() {
axios
.get('/campaigns/new.json')
.then(response => (
this.kits = response.data[0].kits,
)
}
}
然后在掛載的鈎子中:
async mounted() {
await this.getData()
console.log(this.kits)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.