【问题标题】:How to return a response from axios in Vue如何在Vue中从axios返回响应
【发布时间】:2019-07-30 23:07:59
【问题描述】:

我阅读了有关堆栈溢出的所有已回答问题,但仍然无法弄清楚如何进行这项工作。

File1.js

我使用 axios ajax 调用将一些数据发送到服务器,如下所示:

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

这里有我的 Vue 代码,我想在其中获取 ajaxSearchAxios() 的输出并存储在 Vue 数据中。

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

谢谢

【问题讨论】:

    标签: vue.js axios


    【解决方案1】:

    Vue 中来自 axios 的异步调用:

    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();
        }
    });
    

    【讨论】:

    【解决方案2】:

    请记住,您正在处理异步函数,因此您的函数需要以 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'); 
          });
    }
    

    然后把它当作一个promise来处理,而不是把函数赋值给值

    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)
            },
        },
    });
    

    【讨论】:

    • 你能解释一下 ajaxSearchAxios('s','s1').then(result => this.SearchResults = result) 中发生了什么。是结果=ajaxSearchAxios中.then()函数返回的数据
    • 这相当于在 axios Promise 的 thencatch 之间插入另一个 then 调用。当您在 ajaxSearchAxios 函数中返回 axios 承诺时,您可以将进一步的承诺链接到它。
    【解决方案3】:

    我假设调用ajaxSearchAxios 正在工作并且您已正确导入file1。如果是这样,axios返回一个promise,所以尝试返回axios obj并在vue中使用asyncawait等待这样的结果...

    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)
            },
        },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-09
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2019-06-20
      • 2023-02-15
      相关资源
      最近更新 更多