Vue.js 访问key的值

三重C

尝试使用 Vue.js 访问键的值,这对我来说是新的。key.title如果可能,我想使用密钥作为 id 并使用或类似的东西访问标题这是我正在尝试的代码:

HTML

  <ul id="all">
    <li v-for="(song,key) in songs" :class="{ active: song.isActive }" v-bind:id="key">
      {{ key.title }} //Hound Dog
    </li>
  </ul>

Javascript

var vm = new Vue({
  el: '#all',
  data: {
    songs: [
      a:{
        title:'Hound Dog',
        lyrics:'You aint nothing but a hound dog, crying all the time',
        isActive: true 
      },
      b:{
        title:'Long Gone',
        lyrics:'I am long gone today',
        isActive: false
      } 
    ]    
  }
})
伯特

正如我在评论中提到的,您的songs对象不是有效的 javascript 对象。出于本示例的目的,我将其转换为数组。key在这种情况下,您所说的 a只是数组中项目的索引,它只是一个数字,没有任何属性。

var vm = new Vue({
  el: '#all',
  data: {
    songs: [
      {
        title:'Hound Dog',
        lyrics:'You aint nothing but a hound dog, crying all the time',
        isActive: true 
      },
      {
        title:'Long Gone',
        lyrics:'I am long gone today',
        isActive: false
      } 
    ]    
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
  <ul id="all">
    <li v-for="(song, index) in songs" :class="{ active: song.isActive }" v-bind:id="index">
      {{ song.title }} 
    </li>
  </ul>

在第二个示例中,我将歌曲转换为对象。

var vm = new Vue({
  el: '#all',
  data: {
    songs: {
      a: {
        title: 'Hound Dog',
        lyrics: 'You aint nothing but a hound dog, crying all the time',
        isActive: true
      },
      b: {
        title: 'Long Gone',
        lyrics: 'I am long gone today',
        isActive: false
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<ul id="all">
  <li v-for="(song, key) in songs" :class="{ active: song.isActive }" v-bind:id="key">
    {{ song.title }} 
  </li>
</ul>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章