2015-11-28 96 views
1

我正在構建一個簡單的媒體播放器應用程序。這是簡單的應用程序結構:Vue JS:Prop的屬性更改未在子組件中檢測到

|-- 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取出,隨後流傳下來的propscomponents/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替換它,並設置這首新歌的playingtrue

通過這種方法,我期望每一個新的歌曲播放時間,其組件的<tr>.playing類激活,當其他人都將變暗,由於.playing類中刪除突出顯示。可悲的是,事實並非如此。很顯然,歌曲'playing屬性根本沒有被監視,所以即使它在每個Song對象中都被更改,CSS類也不會被切換。

我在這裏做錯了什麼?

+0

你能提供一個jsfiddle嗎? –

+0

我不確定一個簡單的小提琴是否可以處理這個問題。如上所述,這是一個簡化(非常簡化)的應用程序版本,現在它實際上有50個文件,並且有一個PHP後端。 –

回答

2

您可以嘗試將一個屬性(如playingSong)添加到app.vue,並將其作爲synced property傳遞給song-item模板。

然後,而不是this.$root.play(this.song)應該設置this.playingSong = this.song

,然後創建一個計算的屬性來檢查這首歌

computed: { 
    playing() { 
     return this.playingSong === this.song 
    } 
} 

希望它能幫助。

+0

這個方法雖然有點不夠有效,但比起像'thisSong'四處傳遞更好的方法嗎? –

+0

也許你可以像這樣訪問它'this。$ root.playingSong' –

+0

對,我會試試這個。謝謝! –

相關問題