当前位置: 首页 > Web前端 > vue.js

vue全家桶(3.1)

时间:2023-03-31 21:41:27 vue.js

4.数据请求#4.1。什么是公理?Axios是用于浏览器和nodejs的基于Promise的HTTP客户端。它有以下特点:从浏览器创建XMLHttpRequest从node.js发送http请求支持PromiseAPI拦截请求和响应转换请求和响应数据取消请求自动转换JSON数据客户端支持在vue全家桶中防止CSRF/XSRF。建议使用它。说白了,就是用来发送请求,和后台交互的#4.2。简单使用1.安装axiosnpminstallaxios--save2。使用axios发送get请求在组件内部导入axios,这里以Demo1.vue为例:importaxiosfrom'axios'在createdcreated(){axios.get('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list').then((response)=>console.log(response))}完整代码:上面代码中打印出来的内容是一个对象,里面的内容结构是:{//`data`是服务器提供的响应data:{},//`status`是来自服务器响应的HTTP状态码status:200,//`statusText`是HTTP状态信息fromtheserverresponsestatusText:'OK',//`headers`服务器响应headers的headers:{},//`config`为请求提供的配置信息config:{}}知识补充:后端地址代码中使用的是使用一个在线的mock数据生成工具伪造的,具体工具如下easy-mock地址:https://easy-mock.commockjs文档:https://github.com/nuysoft/Mock/wikimockjs案例:http://mockjs.com/examples.htmlEasy-mock简单使用教程:http://blog.nodeing.com/archives/87.html上面的例子中,使用了get方法来请求数据,get方法是默认的,所以你也可以写成axios('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list').then((response)=>console.log(回应e))3.使用axios发送post请求接下来可以试试Let'ssendpost方法。用法类似jquery中的ajax方法axios({method:'post',url:'https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/add'})。then((response)=>console.log(response))4.错误处理你需要在catch中处理错误,例如:axios({method:'post',url:'https://easy-mock.com/模拟/5c23887d3671d47be5ea8d66/axiosdemo/course/add/1'}).then((response)=>console.log(response)).catch((err)=>console.log(err))5.传参方法get请求方法传parameter,只需配置params选项即可:30}}).then((response)=>console.log(response))注意:params中的内容作为querystring和url连同post请求一起传参,配置data选项axios({方法:'post',url:'https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/add',数据:{title:'htmlbestentry',计数:80}}).then((response)=>console.log(response)).catch((err)=>console.log(err))注:数据内容作为请求体#4.3发送。请求方法的别名是为了方便,对所有支持的请求方法别名axios.request(config)axios.get(url[,config])axios.delete(url[,config])axios.head(url[,config])axios.post(url[,data[,config]]])axios.put(url[,data[,config]])axios.patch(url[,data[,config]])例如,我们本来是用axios发送get请求的,我们这样写的axios({m方法:“获取”,网址:“https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list”,参数:{id:10}}).then((response)=>console.log(response))使用相应的别名发送,你可以这样写:axios.get('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list',{params:{id:10}}).then((response)=>console.log(response))其他请求方式与上面的例子#4.4类似。处理并发请求有时候,你想一次执行多个请求,可以使用all方法函数http1(){returnaxios.get('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list')}functionhttp2(){returnaxios.post('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/update')}axios.all([http1(),http2()]).then((response)=>{//这里response返回一个数组,包含两个请求的返回结果console.log(response)})将上面代码返回的结果放到一个数组中。如果想单独取出结果,可以使用axios.spread方法axios.all([http1(),http2()])。then(axios.spread((res1,res2)=>{//res1对应http1的请求结果res2对应http2的请求结果console.log(res1,res2)}))