[Vuejs]-VueJS return value from promise in method section of component

3👍

First of all post returns a promise and it is performed asynchronously. getStatus will return before the anonymous function you pass in to post will be called. It cannot return the string value. For the caller of getStatus() to get the value of the returned string, you must use then(). I suggest you research asynchronous programming and promises in javascript a bit further to understand callbacks and when they are run.

Secondly, you typically should not bind a prop to the result of a method/function. Props almost always should be bound to a data field or computed.

I suggest you change the post handler to set a data field and bind to that instead.

:status="personsStatus"

data: {
    return {
        person: ??, //i dont know where this comes from
        personStatus: 'unknown', //some default value. maybe '?'
    };
},
mounted() {
    this.loadStatus(this.somePerson);
},
methods: {
    loadStatus(person) {
        axios.post(...)
            .then((resp) => {
                //your more complex logic here, 
                //but instead of returning a string, 
                //set the personStatus field like the following:
                this.personStatus = 'safe';
            });
    }
}

This may require you to create a child component to do this work if you have multiple person instances.

Leave a comment