【问题标题】:How to post from array mutiple request with axios in vuejs?如何在 vuejs 中使用 axios 从数组中发布多个请求?
【发布时间】:2018-06-29 02:41:25
【问题描述】:

我尝试使用 axios 从数组发布到 api php 文件并一一获取响应,而不仅仅是一个请求。我读过一些关于 axios.all() 的内容,但不知道我是 javascript 新手。

<div id="app">
    <center>
<div id="area">
   <textarea v-model="sent" name="sent" id="sent" cols="30" rows="10" class="form-control">
   </textarea>
    <br>
    <button v-on:click="insert" class="btn btn-default">Send</button>
</div>

<div id="good" v-for="message of messages">
    <span><h2>Good</h2></span>

        {{ message }}

</div>

</center>
</div>

这里是 vuejs 代码。

<script>
     new Vue({
 el:'#app',
 data:{
     sent:[],
     messages:[]
 },
         methods:{
           insert:function (){
               const vm = this;
               splitz.forEach(function(entry){
               axios.post('/one.php', {
                   sent: vm.entry
               }).then(response => {
                   vm.messages.push(response.data.onefinal) ;
                       console.log(response.data);
                   }
               ).catch(function(error){ console.log(error); });
               }
            }
         },
         computed:{
             splitz: function () {
                 return this.sent.split('\n')
             }
         }
    });
</script>

【问题讨论】:

    标签: javascript php vue.js axios


    【解决方案1】:

    你可以这样做:

    // Create an array of post requests from splitz array
    var requests = splitz.map(entry => axios.post('/one.php', { sent: this.entry }))
    
    // Send all requests using axios.all
    axios.all(requests)
    .then(results => results.map(response => response.data.onefinal))
    .then(newMessages => {
        console.log('New Messages:', newMessages)
        this.messages.push.apply(this.messages, newMessages)
    })
    

    编辑:逐一发送请求:

    insert: function() {
    
        var vm = this;
    
        function sendRequest(arr, i) {
            var entry = arr[i];
            axios.post('/one.php', { sent: entry }).then(function (response) {
                vm.messages.push(response.data.onefinal);
                if (i < arr.length - 1) {
                    sendRequest(arr, ++i);
                }
            })
                .catch(function (error) {
                    console.log(error);
                });
        }
    
        sendRequest(this.splitz, 0);
    
    }
    

    【讨论】:

    • 对于数组中的每个字符串,它是否像发送请求然后得到响应等等一样进行?或者只是按时发送整个数组。
    • 这将同时发送所有请求并将所有响应收集到一个数组中。如果您想一一发送,请告诉我,我会编辑答案。
    • 是的,一一喜欢发送请求获取响应发送请求获取响应您能帮忙吗?谢谢
    • 谢谢 不好意思问我在插入方法中放在哪里?
    • 是的,你可以用它替换insert方法的内容。
    猜你喜欢
    • 2020-05-12
    • 2021-08-11
    • 1970-01-01
    • 2018-07-01
    • 2019-09-07
    • 2020-08-06
    • 1970-01-01
    • 2018-01-14
    • 2019-09-10
    相关资源
    最近更新 更多