首页 新闻 会员 周边

vue-resource获取豆瓣API用v-for渲染列表出错

0
悬赏园豆:50 [已解决问题] 解决于 2018-03-15 10:06

<template>
<div class="NowPlay">
  <div v-if="movie">
    <div v-for="(item,index) in movie" class="NowPlay_list box-shadow-1px">
      <div><img :src="item.images.small" class="list_img"></div>
      <div class="list_massgage">
      <div>{{item.title}}</div>
      <div>{{item.rating.average}}</div>
      <div>{{item.directors[0].name}}</div>
      <div>{{item.casts[0].name}}</div>
      <div>{{(item.collect_count/10000).toFixed(1)}}万人看过</div>
    </div>
  </div>
</div>
</div>
</template>

<script>
export default{
  data: function() {
    return {
      movie:{}
  }
},
  created: function() {
    this.$http.jsonp('https://api.douban.com/v2/movie/in_theaters', {},
    {headers: {},emulateJSON: true }).then((response) => {
    var _this = this;
    _this.movie = response.body.subjects;
    }),() =>{
    console.log("error")
   };
  }
}
</script>

<style>
.NowPlay_list{
display: flex;
align-items: center;
width: 100%;
height: 170px;
}
.list_img{
width: 105px;
height: 150px;
margin-left: 10px;
}
.box-shadow-1px {
box-shadow: inset 0px -1px 1px -1px #c8c7cc;
}
.list_massgage{
display: flex;
justify-content: space-between;
flex-direction: column;
}
</style>

 

 

 

问题就在

<div>{{item.casts[0].name}}</div>这句提示

TypeError: Cannot read property 'name' of undefined

不知是我解析json错误还是其他问题

晓贰的主页 晓贰 | 初学一级 | 园豆:155
提问于:2018-03-14 10:27
< >
分享
最佳答案
0

item.casts 中没有name这个属性;判断一下这个如果name为undefined 就给空字符串

收获园豆:50
悟行 | 专家六级 |园豆:12559 | 2018-03-14 11:09

取到的数据是有name这个键值的

"casts": [
  {
    "alt": "xxx",
    "avatars": {
      "small": "//xxx",
      "large": "xxx",
      "medium": "xxx"
    },
    "name": "xxx",
    "id": "xxx"
},

{

  ........

},

{

  ........

}

 

 

{{item.casts[0].name}}这样取为什么会错误呢

晓贰 | 园豆:155 (初学一级) | 2018-03-14 11:14

@晓贰: 不要用[0]取值,再加个循环item.casts 就可以了。

悟行 | 园豆:12559 (专家六级) | 2018-03-14 14:05

@晓贰: 例如:

<p>
    <span v-for="a in musics.author">
        {{ a.name }}
    </span>
</p>
悟行 | 园豆:12559 (专家六级) | 2018-03-14 14:08
其他回答(1)
0

调用ajax请求是异步的,肯定是先加载,第一次加载的时候你这个item里并没有数据,所以娶不到casts[0],后来数据来了,就可以渲染了。你v-if的那个地方不要写movie,写movie.length就行了。因为数组也是object类型的,永远是true

马战鹏 | 园豆:432 (菜鸟二级) | 2018-03-14 13:52
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册