无法调用组件的方法

时间:2018-01-15 12:28:39

标签: laravel-5 vue.js vue-component

在我的Laravel-Vuejs项目中使用EventBus。在成功ItemCreate创建后,我正在从Item组件发出项目更新事件。在同一页面上,我正在使用ItemList组件,该组件显示已创建的Items

列表

以下是代码:

app.js文件

require('./bootstrap');

window.Vue = require('vue');
window.EventBus = new Vue();

Vue.component('item-list', 
  require('./components/entities/item/ItemList'));
Vue.component('item-create', 
  require('./components/entities/item/ItemCreate'));

const app = new Vue({
  el: '#app'
});

ItemCreate.vue组件

export default {
    data: function () {
        return {
            itemName: ''
        }
    },
    methods: {sendItemData: function () {
            axios.post('/dashboard/item', {
                name: this.itemName
            })
                .then(response => {
                    if (response.status === 201) {
                        toastr.success('Item created successfully!', {timeout: 2000});
                        EventBus.$emit('items-updated');
                    }
                })
                .catch(error => {
                    toastr.error(error, 'Ooops! Something went wrong!');
                })
        }
    }
}

ItemList.vue组件

export default {
    data: function () {
        return {
            items: [],
        }
    },
    methods: {
        getItems: function () {
            axios.get('/dashboard/items')
                .then(response => {
                    this.items = response.data;
                })
                .catch(error => {
                    toastr.error(error, 'Ooops! Something went wrong!');
                })
        }
    },
    mounted() {
        this.getItems();
        EventBus.$on('items-updated', function () {
            this.getItems();
        });
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个普通的JS错误。工作代码:

ItemList.vue组件上的

export default {
data: function () {
    return {
        items: [],
    }
},
methods: {
    getItems: function () {
        axios.get('/dashboard/items')
            .then(response => {
                this.items = response.data;
            })
            .catch(error => {
                toastr.error(error, 'Ooops! Something went wrong!');
            })
    }
},
mounted() {
    this.getItems();
    let vm = this;
    EventBus.$on('items-updated', function () {
        vm.getItems();
    });
}

}