Vue.js 从另一个组件调用方法

Vue.js Call method from another component

本文关键字:调用 方法 组件 另一个 js Vue      更新时间:2023-09-26

我有 2 个组件。如何在createProject()方法中调用fetchProjectList()方法。

第一个组件:

Vue.component('projects', {
    template: '#projects-template',
    data: function () {
        return {
            list: []
        }
    },
    ready: function () {
        this.fetchProjectList();
    },
    methods: {
        fetchProjectList: function () {
            resource.get().then(function (projects) {
                this.list = projects.data;
            }.bind(this));
        }
    }
});

第二个组件

Vue.component('createProjects', {
    template: '#create-projects-template',
    methods: {
        createProject: function () {
            resource.save({}, {name: this.name}).then(function () {
                this.fetchProjectList()
            }.bind(this), function (response) {
                // error callback
            });
        }
    }
});

你没有,或者更确切地说,你不应该。 组件不应该以如此直接的方式依赖于其他组件。

您应该将此方法提取到 mixin 中,或者将其保留在导入到每个组件中自己的对象中。

阅读商店模式:http://vuejs.org/guide/application.html#State_Management