Search code examples
javascriptvue.jsvue-resource

Vue.js Call method from another component


I have 2 components. How can I call fetchProjectList() method in createProject() method.

First component:

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));
        }
    }

});

Second component

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
            });
        }
    }
});

Solution

  • You don't, or rather you shouldn't. components should not depend on other components in such a direct way.

    You should either extract this method into a mixin, or keep it in it's own object which you import into each component.

    Read up on the store pattern: http://vuejs.org/guide/application.html#State_Management