vuejs2向组件添加事件侦听器

时间:2017-12-27 09:07:13

标签: javascript vue.js vuejs2 laravel-5.4

我的页面中有回复组件和 newReply 组件。添加newReply后,我会在全局vue消息总线上发出一个事件,通知回复组件已添加新回复,以便重新加载和重新呈现。

methods: {
  updateReplyList: function(newReply){
          window.vueMessageBus.$emit('notifyingrepliescomponent',newReply);
        },
}

我在回复组件的created()钩子中附加了 notifyingrepliescomponent 事件的事件监听器。

更新代码SNIPPET

//file: replies.vue

methods: {

        fetch: function(url = null){
            let vm = this;

            if(!url)
            {
                axios.get(route('replies.paginated',{ 'thread' : this.thread_id }))
                .then(function(serverResponse){
                    vm.replies_with_pagination = serverResponse.data;           
 //'replies_with_pagination' holds the paginated collection returned by laravel for the current paginated page
                });                                                             

          }                                                                 

         else
            {
              var page = url.match(/\?page=(\d+)/i)[1];
              axios.get(route('replies.paginated',{ 'thread' : this.thread_id, 'page' : page }))
               .then(function(serverResponse){
                    vm.replies_with_pagination = serverResponse.data; 
                });     
            }                                                                


        },

        reloadNew: function(url){
            this.fetch(url);
            window.scrollTo(0,0);
        },
    },

created() {
        this.fetch();

        window.vueMessageBus.$on('notifyingrepliescomponent',newReply => {
           console.log('added object: ' + newReply);
           this.all_reply_items.push(newReply);

           this.reloadNew(route('replies.paginated',{ 'thread' : this.thread_id, 'page' : this.pageForQueryString }));

           this.$emit('repliescountchanged',this.all_reply_items.length);
        });        
    },

除了第一次以外,整个系统都有效。也就是说,如果没有对线程的回复,并且我添加了新的回复,则回复组件不会重新加载。但对于随后的回复,这很好。

我猜这是我的事件监听器的问题?有人可以帮忙吗?

TIA,Yeasir

0 个答案:

没有答案