javascript - vue 獲取json數(shù)據(jù)的某個(gè)屬性成功,卻報(bào)錯(cuò)
問題描述
使用vue獲取豆瓣電影的某個(gè)電影詳細(xì)信息,數(shù)據(jù)已經(jīng)獲取成功,average屬性也在頁面上顯示成功,但是控制臺(tái)卻報(bào)錯(cuò)。
<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'><!--就是這部分代碼報(bào)錯(cuò)--> <mt-cell><span v-if=’detail.rating.average!=0’>{{detail.rating.average}}分</span><span v-else>暫無評(píng)分</span><img v-for='starNum in Math.round(detail.rating.average/2)' slot='icon' src='http://www.aoyou183.cn/static/images/ratingStar.png' 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>
問題解答
回答1:因?yàn)楂@取數(shù)據(jù)是異步的,而當(dāng)你模板掛載完后,你的數(shù)據(jù)還沒獲取到,導(dǎo)致detail.rating.average沒定義
比較好的方式是你在data中就定義好你在模板中有引用到的值
data() { detail: {rating: { average: ’’} }}回答2:
你在模板中書寫了 v-if=’detail.rating.average!=0’,但組件初始化時(shí) data 內(nèi)屬性卻是 detail: [],從而 detail.rating 就是 undefined,因此在使用 detail.rating.average 時(shí)就會(huì)產(chǎn)生錯(cuò)誤了。
一個(gè)解決方案是,在 data 中即預(yù)先按照 v-if 內(nèi)的嵌套結(jié)構(gòu),定義好 detail 數(shù)據(jù)結(jié)構(gòu)即可。
相關(guān)文章:
