简体   繁体   中英

Vue methods mixins

I have method getNames inside my mixins file that returns names.

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;

From my single template file I have imported the mixins/methods file. Now my problem is how can I get the return object data from getNames method. Coz when I tried to

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

getNames method just returns a Promise

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

The axios.get() call is asynchronous and it returns a Promise . It does not return the value from the anonymous function passed to the chained then method.

In order to access that value, you can chain a then method to the returned Promise , like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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