尝试使用 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] 删除。
我来说两句