Use vue to obtain the detailed information of a certain movie in Douban Movies. The data has been successfully obtained, and the average attribute is also displayed successfully on the page, but the console reports an error.
<template>
<p id="movie-detail">
<p class="movie-card">
<h2>{{detail.title}}</h2>
<h4>({{detail.original_title}})</h4>
<section class="movie-intro">
<p 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>
</p>
</section>
</p>
</p>
</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>
Because obtaining data is asynchronous, and after your template is mounted, your data has not been obtained yet, resulting in
detail.rating.average
not being definedA better way is to define the values you reference in the template in
data
You wrote
v-if='detail.rating.average!=0'
in the template, but when the component is initialized, the internal attribute of data isdetail: []
, sodetail.rating
is undefined, so An error will occur when usingdetail.rating.average
.One solution is to define the detail data structure in data in advance according to the nested structure within
v-if
.