【问题标题】:Vue 3.0 Use Var as KeyVue 3.0 使用 Var 作为 Key
【发布时间】:2021-05-26 22:55:36
【问题描述】:

我尽力理解这个问题:

我可以像这样制作一个 v-for:

<div v-for="playlistItem of playlists.PLDk0_ZYOcqxEq5ZxXAI5FiVL79hk2oSua.items">
        {{playlistItem.snippet.title}}
      </div>

您可以看到我有一个播放列表 ID 用作播放列表对象中的键 - 这工作正常。

当我尝试这样做时:

 <div v-for="playlist of channel.items" :key="playlist.id">
  <div v-if="playlist.contentDetails.itemCount && playlist.status.privacyStatus === 'public'">
    <div>{{playlist.snippet.title}}</div>
    <div>{{playlist.id}}</div>
    <div>
      <div class="content">Content:</div>
      <div v-for="playlistItem of playlists[playlist.id].items">
        {{playlistItem.snippet.title}}
      </div>
    </div>
    <hr>
  </div>
</div>

应用程序阻塞并告诉我“无法读取未定义的属性 'items'”。

{{playlist.id}} 给我搜索到的播放列表,当我这样做时: {{playlists[playlist.id]}} 它显示页面上的对象。

但是这个 {{playlists[playlist.id].items}} 不能使用所以我错过了什么?

背景:

<script>
// @ is an alias to /src
import channel from '@/../public/cache/channel.json'
import playlists from '@/../public/cache/playlists/'

export default {
  name: 'Home',
  components: {
    channel, playlists
  },
  data(){
    //console.log(channel)
    console.log(playlists)
    return{
      channel, playlists
    }
  }
}
</script>

频道在 json 中包含 youtube 频道数据,对于播放列表,我有这样的播放列表对象:

{
    "PLDk0_ZYOcqxEqFirstKey" : {"kind":"","etag:"","items":[...]},
    "PLDk0_ZYOcqxEqanotherKey" : {"kind":"","etag:"","items":[...]},
}

所以实际上我尝试从播放列表对象中获取具有此 for 循环 ID 的对象,然后循环遍历其项目: 播放列表。“variableIdFormParentLoop”.items

代码沙盒链接:Code Sandbox

【问题讨论】:

    标签: javascript json vue.js object variables


    【解决方案1】:

    playlists 中缺少来自channel.items[] 的某些播放列表 ID,因此当遇到这些 ID 时,playlists[playlist.id]undefined,从而导致您观察到的错误。

    一种解决方案是根据playlists[playlist.id]有条件地渲染播放列表数据:

    <template v-if="playlists[playlist.id]">
      <div class="content">Content:</div>
      <div v-for="playlistItem of playlists[playlist.id].items" :key="playlistItem.snippet.id">
        {{playlistItem.snippet.title}}
      </div>
    </template>
    

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多