Vue JS:在子组件内未检测到Prop的属性更改

时间:2015-11-28 10:09:00

标签: vue.js

我正在构建一个简单的媒体播放器应用。这是简化的应用程序结构:

|-- 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.vuecomponents/main-wrapper/main/content/index.vuecomponents/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类也永远不会被切换。

我在这里做错了什么?

1 个答案:

答案 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
    }
}

希望它有所帮助。

相关问题