我正在构建一个简单的媒体播放器应用。这是简化的应用程序结构:
|-- app.vue
|-- components
| |-- main-wrapper
| | |-- index.vue
| | |-- main-content
| | | |-- albums.vue
| | | |-- artists.vue
| | | |-- index.vue
| | | |-- songs.vue
| | `-- sidebar
| | `-- playlists.vue
| |-- shared
| `-- song-item.vue
`-- main.js
歌曲列表从顶级app.vue
获取,随后以props
传递给components/main-wrapper/index.vue
,components/main-wrapper/main/content/index.vue
和components/main-wrapper/main/content/songs.vue
,按顺序。所有props
都定义为动态 - 例如:list="songs"
- 并在子组件中注册 - 例如props: ['list']
等。
现在在songs.vue
子组件中我有这段代码:
<template>
<tbody>
<tr is="song-item" v-for="song in list" track-by="id" :song="song"></tr>
</tbody>
</template>
<script>
import songItem from '../../shared/song-item.vue';
export default {
props: ['list'], // register the prop from parent, as said above
replace: false,
components: { songItem }
};
</script>
每个songItem
都是一个组件实例(?),它通过检查song.playing
来设置自己的状态,即突出显示正在播放的文本。
<style>.playing { color: #f00; }</style>
<template>
<tr :class="{ 'playing': song.playing }">
<td class="title">{{ song.title }}</td>
<td class="controls">
<i v-show="!song.playing" class="fa fa-play-circle" @click="play"></i>
<i v-show="song.playing" class="fa fa-pause-circle" @click="pause"></i>
</td>
</tr>
</template>
<script>
export default {
props: ['song'], // again, register the prop from parent
methods: {
play() {
this.$root.play(this.song);
}
}
}
</script>
现在,this.$root.play(this.song)
会将当前歌曲的playing
属性设置为false
,将其替换为新提供的this.song
参数,并将此新歌设为playing
} true
。
通过这种方法,我希望每次播放新歌时,其组件的<tr>
都会在.playing
类被激活的情况下突出显示,而其他组则会因.playing
而变暗。 1}}类已删除。可悲的是,事实并非如此。显然,歌曲'playing
属性根本没有被观看,所以即使它在每个Song
对象中被更改,CSS类也永远不会被切换。
我在这里做错了什么?
答案 0 :(得分:2)
您可以尝试向playingSong
添加属性(例如app.vue
),并将其作为synced property传递给song-item
模板。
然后,您应该设置this.$root.play(this.song)
this.playingSong = this.song
然后,创建一个计算属性来检查歌曲
computed: {
playing() {
return this.playingSong === this.song
}
}
希望它有所帮助。