Aseem
Aseem

Reputation: 6769

How to return a response from axios in Vue

I read all answered questions on stack overflow but still unable to figure out how to make this work.

File1.js

I send some data to server using axios ajax call as follows:

function ajaxSearchAxios(searchType,searchText){ 
    var searchResults=[];
    axios({
        method: 'post',
        url: 'ajaxSearch/',
        data: {
              searchType: searchType,
              searchText: searchText,
            },
        responseType: 'json',
      })
      .then ( function (response){
          searchResults = response.data['searchResults']; console.log('JS searchResults=',searchResults[0].value) //this prints nicely to the console
          return searchResults

      })
      .catch ( function (error){
        console.log('ajaxSearch error'); 
      });
}

File2.js

Here I have my Vue code where I want to take output of ajaxSearchAxios() and store in Vue data.

new Vue({
    el:'#id_1',
    data:{
            SearchResults:[],
    },
    methods:{
        ajaxSearch:function(searchType){
            this.SearchResults= ajaxSearchAxios('s','s1');
            console.log('VUE =',this.SearchResults[0].value)
        },
    },
});

Thanks

Upvotes: 4

Views: 15730

Answers (3)

user11766756
user11766756

Reputation:

Asynchronous calls from axios in Vue:

var v1 = new Vue({
    el: '#id_mainPage',
    data: {
        branches: [''],
    },
    methods: {
        ajaxAxiosGetFunc: async function (url) {
            var output = '';
            await axios({
                method: 'get',
                url: url,
                data: {},
                responseType: 'json',
            })
                .then(function (response) {
                    output = response.data;
                }.bind(this))
                .catch(function (error) {
                    console.log('ajax get branches error');
                });
            return output
        },

        getAllBranchNames: async  function(){
            var output = await this.ajaxAxiosGetFunc('http://localhost:9977/get_branches');  // called asynchronously to wait till we get response back
            this.branches = output['branches'];
        },
    },
    mounted: function () {
        console.log('Vue mounted');
        this.getAllBranchNames();
    }
});

Upvotes: 4

Daniel
Daniel

Reputation: 35684

Remember, you're dealing with asynchronous functions, so your function needs to return and handle the functionality as a Promise

function ajaxSearchAxios(searchType,searchText){ 
    return axios({ // <--- return the PROMISE
        method: 'post',
        url: 'ajaxSearch/',
        data: {
              searchType: searchType,
              searchText: searchText,
            },
        responseType: 'json',
      })
      .then ( function (response){
          return response.data['searchResults']; 
      })
      .catch ( function (error){
        console.log('ajaxSearch error'); 
      });
}

and then handle it as a promise, instead of assigning the function to value

new Vue({
    el:'#id_1',
    data:{
            SearchResults:[],
    },
    methods:{
        ajaxSearch:(searchType) => {
            // execute axios promise and on success, assign result to var
            ajaxSearchAxios('s','s1').then(result => this.SearchResults = result)
        },
    },
});

Upvotes: 12

Mulhoon
Mulhoon

Reputation: 1902

I assume calling ajaxSearchAxios is working and you've imported file1 correctly. If so, Axios returns a promise, so try returning the axios obj and using async and await in vue to wait for the result like this...

function ajaxSearchAxios(searchType,searchText){ 
    var searchResults=[];
    return axios({
        method: 'post',
...
new Vue({
    el:'#id_1',
    data:{
            SearchResults:[],
    },
    methods:{
        ajaxSearch: async searchType => {
            this.SearchResults = await ajaxSearchAxios('s','s1');
            console.log('VUE =',this.SearchResults[0].value)
        },
    },
});

Upvotes: 1

Related Questions