Vue.js访问密钥

时间:2017-07-21 15:34:35

标签: vue.js

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

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
      } 
    ]    
  }
})

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,您的songs对象不是有效的javascript对象。为了这个例子的目的,我把它转换成了一个数组。在这种情况下,您所谓的key只是数组中项目的索引,它只是一个数字,它没有任何属性。

&#13;
&#13;
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
      } 
    ]    
  }
})
&#13;
<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>
&#13;
&#13;
&#13;

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

&#13;
&#13;
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
      }
    }
  }
})
&#13;
<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>
&#13;
&#13;
&#13;

相关问题