简体   繁体   English

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

[英]Vue.js Call method from another component

I have 2 components. 我有2个组成部分。 How can I call fetchProjectList() method in createProject() method. 如何在createProject()方法中调用fetchProjectList() createProject()方法。

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

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. 您应该将此方法提取到mixin中 ,或将其保留在自己的对象中,然后将其导入每个组件。

Read up on the store pattern: http://vuejs.org/guide/application.html#State_Management 阅读商店模式: http : //vuejs.org/guide/application.html#State_Management

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM