您的位置:首頁技術文章
文章詳情頁

javascript - vue 獲取json數據的某個屬性成功,卻報錯

瀏覽:102日期:2023-02-18 08:56:47

問題描述

使用vue獲取豆瓣電影的某個電影詳細信息,數據已經獲取成功,average屬性也在頁面上顯示成功,但是控制臺卻報錯。

<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='http://www.wxshucaidpc.com/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>

javascript - vue 獲取json數據的某個屬性成功,卻報錯

問題解答

回答1:

因為獲取數據是異步的,而當你模板掛載完后,你的數據還沒獲取到,導致detail.rating.average沒定義

比較好的方式是你在data中就定義好你在模板中有引用到的值

data() { detail: {rating: { average: ’’} }}回答2:

你在模板中書寫了 v-if=’detail.rating.average!=0’,但組件初始化時 data 內屬性卻是 detail: [],從而 detail.rating 就是 undefined,因此在使用 detail.rating.average 時就會產生錯誤了。

一個解決方案是,在 data 中即預先按照 v-if 內的嵌套結構,定義好 detail 數據結構即可。

標簽: JavaScript
相關文章:
国产综合久久一区二区三区