Vuejs2 在模板尝试打印数据之前,如何等待API响应?
我正在尝试打印API响应中的venture.city。我的代码可以工作,但它会在页面加载时尝试打印venture.city,这会导致控制台错误“无法读取null的属性'city' 如何打印单个场所的API响应而不出现此控制台错误 我查看了Vue生命周期(),尝试了v-if和其他一些我在谷歌上发现的东西,但似乎没有任何效果Vuejs2 在模板尝试打印数据之前,如何等待API响应?,vuejs2,Vuejs2,我正在尝试打印API响应中的venture.city。我的代码可以工作,但它会在页面加载时尝试打印venture.city,这会导致控制台错误“无法读取null的属性'city' 如何打印单个场所的API响应而不出现此控制台错误 我查看了Vue生命周期(),尝试了v-if和其他一些我在谷歌上发现的东西,但似乎没有任何效果 <template> <div class="venue"> <div> test: {{
<template>
<div class="venue">
<div>
test: {{ venue.city }}
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "Venue",
data() {
return {
venue: null
}
},
mounted() {
console.log(this.$route.params.id);
axios.get("http://localhost:8080/venues/" + this.$route.params.id)
.then(response => (this.venue = response.data))
.catch(error => (console.log(error)));
}
}
</script>
测试:{{地点.城市}
从“axios”导入axios;
导出默认值{
名称:“场馆”,
数据(){
返回{
地点:空
}
},
安装的(){
console.log(此.route.params.id);
axios.get(“http://localhost:8080/venues/“+this.$route.params.id)
.然后(response=>(this.vention=response.data))
.catch(error=>(console.log(error));
}
}
Vue有一个类似于mounted的生命周期挂钩,即在mounted之前,它基本上允许您在呈现模板之前执行一些操作,请参见以下内容:
beforeMounted () {
console.log(this.$route.params.id);
axios.get("http://localhost:8080/venues/" + this.$route.params.id)
.then(response => (this.venue = response.data))
.catch(error => (console.log(error)));
}
您还可以使用在then和catch中更新的加载变量,然后根据该加载变量显示模板,如下所示:
<template>
<div>
<div v-if="loading">loading...</div>
<template v-else>
<div class="venue" v-if="loadState === 'DONE'">
<div>test: {{ venue.city }}</div>
</div>
<div class="error-message" v-else-if="loadState === 'ERROR'">
Ooops. Something happened
</div>
<div class="loading-message" v-else>
Loading...
</div>
</template>
</div>
</template>
希望有帮助:)我发现最可靠的方法是在内部处理状态。这提供了错误处理和加载反馈 在我的真实应用程序中,我通常使用枚举状态和vuex来处理远程数据,加载状态也是vuex的一部分,但下面是一个使用您的代码的简单示例
测试:{{地点.城市}
哎呀。出事了
加载。。。
从“axios”导入axios;
导出默认值{
名称:“场馆”,
数据(){
返回{
地点:空,
loadState:null,
};
},
安装的(){
console.log(此.route.params.id);
this.loadState='LOADING';
axios
.get(“http://localhost:8080/venues/“+this.$route.params.id)
。然后(响应=>{
this.vention=response.data;
this.loadState='DONE';
})
.catch(错误=>{
this.loadState='ERROR';
console.log(错误)
});
}
};
非常感谢您,这是一个很好的实现,而且很有效。从中学到了一些新东西!
beforeMounted () {
console.log(this.$route.params.id);
axios.get("http://localhost:8080/venues/" + this.$route.params.id)
.then(response => (){
this.loading = false
})
.catch(error => () {
this.loading = false
});
}