2016-02-11 42 views
2

我有2個組件。如何在createProject()方法中調用fetchProjectList()方法。Vue.js從另一個組件調用方法

第一部分:

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

這些組件是如何鏈接的?他們有共同的父母嗎? – nils

+0

不,他們沒有共同的父母。我是初學者。 – user3118789

回答

3

你不這樣做,或者說你不應該。組件不應該以這種直接的方式依賴於其他組件。

您應該將此方法提取到mixin中,或將其保存在您導入到每個組件的自己的對象中。

查看商店圖案:http://vuejs.org/guide/application.html#State_Management

+1

根據他們的關係,使用事件也可能是一個很好的解決方案。 – nils