[英]Undefined data variable Vue.js when using axios
this is driving me nuts.这让我发疯。
I'm assigning the value from an axios response to my vue data like this:我将 axios 响应中的值分配给我的 vue 数据,如下所示:
mounted() {
axios
.get('/campaigns/new.json')
.then(response => (
this.kits = response.data[0].kits,
)
)
I can see with vue developer tools that my this.kits has an array of 8 items (correct)我可以使用 vue 开发人员工具看到我的 this.kits 有一个包含 8 个项目的数组(正确)
When I try to use this.kits
afterwards or do console.log(this.kits)
, I get undefined or empty array .当我之后尝试使用this.kits
或执行console.log(this.kits)
时,我得到undefined 或 empty array 。
What the hell am I missing?我到底在想什么? Please help.请帮忙。 Thank you谢谢
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)
will output: console.log(this.kits)
将 output:
your console.log is being executed right after the promise request is initiated, you would have to place it at the end inside the then
block or, as Nicola says, use async await您的 console.log 在 promise 请求启动后立即执行,您必须将其放在then
块内的末尾,或者如 Nicola 所说,使用 async await
try this:尝试这个:
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)
}
Try to wait for your data.尝试等待您的数据。 Move the API call to method:将 API 调用移至方法:
methods: {
getData() {
axios
.get('/campaigns/new.json')
.then(response => (
this.kits = response.data[0].kits,
)
}
}
and then in mounted hook:然后在挂载的钩子中:
async mounted() {
await this.getData()
console.log(this.kits)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.