Vue axios all并发请求

Vue axios all并发请求教程

使用 Vue 的 all 可以同时发送多个 HTTP 的请求,直到所有的请求全部完成之后,触发回调。

Vue axios all并发请求详解

语法

axios.all([req1(), req2(), ...]).then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 }));

参数

参数 描述
req1 我们需要发送的第一个请求。
req2 我们需要发送的第二个请求。
spread 即所有的请求都完成后,服务器的回调。

Vue-resource数据准备

首先,我们在 E:\workspace 目录,创建一个 db.json 文件,输入以下内容:

{ "JavaScript":[ { "id": 1, "category":"ES6", "author": "HaiCoder1" }, { "id": 2, "category":"Vue", "author": "HaiCoder2" } ], "Server":[ { "id": 1, "category":"Docker", "author": "HaiCoder3" }, { "id": 2, "category":"Golang", "author": "HaiCoder4" }, { "id": 3, "category":"Python", "author": "HaiCoder5" } ] }

接着,我们在该目录的地址栏,输入 cmd,打开 cmd 窗口,如下图:

14 vue axios data.png

输入 cmd 之后,直接回车,即可在此目录打开命令行,如下图所示:

15 vue axios data.png

我们在命令行,输入以下命令,启动 jsonserver:

json-server --watch db.json

更过有关 JsonServer 的使用,请参考前面的 JsonServer 教程。

案例

Vue axios all并发请求

使用 Vue-resource all 并发请求

<!DOCTYPE html> <html> <head> <title>Vue-axios all 并发请求</title> <script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <input type="button" value="axios all 请求" @click='allInfo'> <p>嗨客网(www.haicoder.net)</p> </div> </body> <script type="text/javascript"> var vm = new Vue({ el : '#app', data:{ msg: "嗨客网" }, methods:{ updateServer1:function() { return axios.put('http://localhost:3000/Server/1', {'category':'Js', 'author':'HaiCoder11'}).then((data)=>{ console.log(data); }); }, updateServer2:function() { return axios.put('http://localhost:3000/Server/2', {'category':'C', 'author':'HaiCoder12'}).then((data)=>{ console.log(data); }); }, allInfo() { axios.all([this.updateServer1(), this.updateServer2()]).then(axios.spread(function (acct, perms) { axios.get('http://localhost:3000/Server').then((data)=>{ console.log('All Request Done'); console.log(data); }); })); } } }); </script> </html>

我们点击按钮,向 JsonServer 发送请求,请求成功后,浏览器输出如下内容:

16 vue axios all.png

我们发现,Server 下面 id 为 1 的数据被修改了,同时,Server 下面 id 为 2 的数据也被修改了,并且在两个修改完成之后,打印出了最新的数据。

即,我们使用 Axios 的 all 请求,同时完成了 this.updateServer1() 和 this.updateServer2() 的请求,最后两个请求都完成后,调用 axios.spread 里面的回调。

Vue axios all并发请求总结

使用 Vue 的 axios 可以发送 HTTP 的 all 并发请求。Vue axios all 并发请求语法 为:

axios.all([req1(), req2(), ...]).then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 }));