【问题标题】:Can't invoke the component's method无法调用组件的方法
【发布时间】:2018-06-24 02:06:49
【问题描述】:

在我的 Laravel-Vuejs 项目中使用 EventBus。在成功创建 Item 后,我从 ItemCreate 组件发出 items-updated 事件。在同一页面上,我使用了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();
        });
    }
}

【问题讨论】:

  • "this" 指的是不同的东西,具体取决于调用它的时间/地点。如果要使其保持一致,则必须在自己的变量中保存对正确 this 的引用。对于更正的代码,请参阅@lostbyte 的答案。
  • 如果你使用 vue-resource 而不是 axios,这不会发生,因为 vue-resource 甚至在 http 回调方法中也将“this”设置为当前组件。

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


【解决方案1】:

这是一个一般的 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();
    });
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-11
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2015-12-15
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多