如果事件是从$ on方法触发的,则Vuejs DOM不会更新

时间:2018-05-01 15:30:31

标签: vue.js

我猜它必须对Vue做一些事情,而不是检测track对象的变化。

mounted(){
        Event.$emit('requestCurrentTrack');
        Event.$on('currentSong', (data) => this.fetchAlbum(data)); //Data from this method won't output on the screen.

        this.fetchAlbum(); // Data from this method out will output to the screen
    },
methods:{
        fetchAlbum(){
            axios.get('/api/album/'+this.id).then((response)=>{
                this.album = response.data[1][0];
                this.tracks = response.data[0];
                this.artistName = this.tracks[0].artist;
            });
        },
        play(data, index){
            if(data){
              Event.$emit('playTrack', data, index);
            }
        }
}

1 个答案:

答案 0 :(得分:1)

  

您必须了解有关活动总线的更多信息。请查看this article

要使用事件总线,请看下面的内容:

main.js中你必须创建事件总线

import Vue from 'vue'
import App from './App.vue'

export const eventBus = new Vue() //creating the event bus

new Vue({
  el: '#app',
  render: h => h(App)
})

渲染组件,我们将其命名为childOne.vue

<template>
  <div>
    <button @click="clicked">Click Me</button>
  </div>
</template>
<script>
    import { eventBus } from '../main'
    export default {
    name: 'child-one',
    methods: {
      clicked () {
        eventBus.$emit('eventName', 'text passed through event bus') //creating the event with the name eventName and pass a text
      }
    }
  }
</script>

另一个呈现的组件可以将其命名为childTwo.vue

<template>
  <div>
    <!-- some html here -->  
  </div>
</template>
<script>
    import { eventBus } from '../main'
    export default {
    name: 'child-two',
      created() {
        eventBus.$on('eventName', dataPassed => { //listening to event with name eventName
        console.log(dataPassed)
      })
    }
  }
</script>

注意只有在您的组件被渲染时,eventBus才会起作用。为了使这个示例正常工作,您可以通过导入App.vue中的两个组件并注册它们来实现它