javascript - vue 获取json数据的某个属性成功,却报错
本文介绍了javascript - vue 获取json数据的某个属性成功,却报错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
使用vue获取豆瓣电影的某个电影详细信息,数据已经获取成功,average属性也在页面上显示成功,但是控制台却报错。
<template>
<div id="movie-detail">
<div class="movie-card">
<h2>{{detail.title}}</h2>
<h4>({{detail.original_title}})</h4>
<section class="movie-intro">
<div class="left">
<!--就是这部分代码报错-->
<mt-cell>
<span v-if='detail.rating.average!=0'>{{detail.rating.average}}分</span>
<span v-else>暂无评分</span>
<img v-for="starNum in Math.round(detail.rating.average/2)" slot="icon" src="../../static/images/ratingStar.png" width="18" height="18">
</mt-cell>
</div>
</section>
</div>
</div>
</template>
<script>
export default {
data() {
return {
movieID: '',
detail: []
}
},
created: function() {
var that = this;
this.$http.get('http://127.0.0.1:8081/movie/subject/' + that.$route.params.id)
.then(function(response) {
that.detail = response.data;
}).catch(function(error) {
console.log(error);
});
},
mounted: function() {
this.movieID = this.$route.params.id;
}
}
</script>
解决方案
因为获取数据是异步的,而当你模板挂载完后,你的数据还没获取到,导致detail.rating.average
没定义
比较好的方式是你在data
中就定义好你在模板中有引用到的值
data() {
detail: {
rating: {
average: ''
}
}
}
这篇关于javascript - vue 获取json数据的某个属性成功,却报错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文