2017-05-23 35 views
1

我的方法getNames在我的mixins文件中返回名称。Vue方法mixins

import { default as config } from '../config'; 
var methods = { 
    methods: { 
     getNames() { 
      return axios.get(API + API.NAMES) 
      .then((response) => { 
       if(response.status == 200 && typeof(response.data) == 'object') { 
        return response.data; 
       } 
      }); 
     } 
    } 
}; 

export default methods; 

从我的单个模板文件中,我已导入mixins/methods文件。现在我的问题是如何从getNames方法获得返回对象数据。怎么把当我试图

mixins: [ 
      filters, 
      methods 
], 
mounted: function() { 
      var a = this.getNames(); 
      console.log(a); 
     } 

getNames方法只返回一个无极

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} 
__proto__ 
: 
Promise 
[[PromiseStatus]] 
: 
"resolved" 
[[PromiseValue]] 
: 
Object 

回答

2

axios.get()调用是异步的,它返回一个Promise。它不会返回传递给链接的方法的匿名函数的值。

为了访问该值,你可以链then方法返回的Promise,就像这样:

mounted: function() { 
    this.getNames().then(a => { console.log(a) }); 
} 
+0

感谢@thanksd – PenAndPapers