我还在用 Laravel 学习 VueJS,我想做的是从 API 获取类别数据并将其加载到选择下拉列表中,但我发现这个 Axios 请求运行时间太长。
这是代码片段
export default {
data() {
return {
category: 0,
categories: [],
loading: true,
}
},
async created() {
let uri = '/api/getCategory';
axios.get(uri).then(response => {
this.categories = response.data;
console.log('2');
}).catch(error => console.log(error))
.finally(() => {
this.loading = false;
});
console.log('1');
},
methods: {
loadCategories() {
axios.get('/api/getCategory')
.then(response => this.categories = response.data)
.catch(error => console.log(error));
}
}
}
以此为基础。 1 DOM 已加载 2
有没有办法让我的 Axios API 请求在 HTML 完成加载之前先获取数据?
最佳答案
您无法在 created Hook 之前访问 react 数据。 Axios 专为响应式(Reactive)处理而设计,这意味着一旦数据可用,它们就会被显示。 我建议的解决方案如下:
- 例如,您可以请求父组件上的数据并将其存储在localStorage中。然后您可以在应用程序中的任何位置使用它。
将代码保存在created Hook 中。使用计算属性而不是类别来进行即时渲染。
计算:{ 计算类别(){ 返回这个。类别; } }
您绝对必须检查服务器端代码以进行查询增强。
关于javascript - Vue JS,如何使 axios 请求 API 在加载 HTML DOM 组件之前首先运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60033237/