gpt4 book ai didi

javascript - Vue : axios executing synchronously instead of asynchronously on multiple components

转载 作者:行者123 更新时间:2023-12-03 01:59:02 25 4
gpt4 key购买 nike

我试图在创建组件时加载ajax数据,但是,这似乎使得在created()中也通过ajax加载的其他项目在执行以下命令时同步加载而不是异步加载,这个 ajax 请求大约需要 2 秒才能运行,导致之后的所有内容都以同步方式加载。

以下组件从 ajax 调用加载大约需要 2 秒:

组件1.vue

export default {
data: () => {
return { balance: { chips: 0, coins: 0, rewards: 0 } }
},
async created() {
this.balance = (await axios.get('/api/player/balance')).data
}
}

该组件从 ajax 调用加载只需不到一秒的时间:

component2.vue

export default {
data: () => {
return { items: [] }
},
async created() {
this.items = (await axios.get('/api/items')).data
}
}

两者应该异步加载,但它们没有,/api/player/balance 运行,然后 /api/items 运行。

我也尝试过使用 .then() 像这样:

export default {
data: () => {
return { balance: { chips: 0, coins: 0, rewards: 0 } }
},
created() {
axios.get('/api/player/balance').then(function (response) {
this.balance = response.data
})
}
}

当我将 this.balance = ... 包装在 setTimeout 中时,其他项目加载正常。

有没有更好的方法来实现这个ajax请求同步运行?

编辑

使用fetch解决了请求同步加载的问题,并允许它们异步加载。

export default {
data: () => {
return { balance: { chips: 0, coins: 0, rewards: 0 } }
},
async created() {
let response = await fetch('/api/player/balance')
this.balance = await response.json()
}
}

有没有办法用axios做到这一点?

最佳答案

您是否尝试过不使用 awaitawait 表达式会导致 async 函数执行暂停,直到满足 Promise,这会导致其他项目挂起,直到 ajax 调用完成

编辑

你能尝试一下这个和你的其他尝试吗?

axios.get('/api/player/balance').then((response) => {
this.balance = response.data
});

您在 then 部分中使用的回调函数使用 ES5 表示法,其中关键字 this 的作用域仅限于该方法。改用 ES6 表示法就可以了。或者您可以将 this 保存到一个新变量中,并相应地使用它,如下所示

const self = this;
axios.get('/api/player/balance').then(function(response) {
self.balance = response.data
});

尽管如此,(对我来说)最佳实践是在 mounted() 中更新模型,而不是 created()

关于javascript - Vue : axios executing synchronously instead of asynchronously on multiple components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com