• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

vue axios数据请求get、post方法及实例详解

vue 搞代码 4年前 (2022-01-08) 18次浏览 已收录 0个评论

axios是一个基于Promise,同时支持浏览器端和Node.js的HTTP库,常用于Ajax请求。这篇文章主要介绍了vue axios数据请求get、post方法的使用 ,需要的朋友可以参考下

我们常用的有get方法以及post方法,下面简单的介绍一下这两种请求方法

vue中使用axios方法我们先安装axios这个方法

npm install --save axios

安装之后采用按需引入的方法,哪个页面需要请求数据就在哪个页面里引入一下。

import axios from 'axios'

引入之后我们就可以进行数据请求了,在methods中创建一个方法

 methods:{ getInfo(){ let url = "url" axios.get(url).then((res)=>{ console.log(res) }) } }

然后我们在mounted这个生命周期中进行调用

本文来源gaodai^.ma#com搞#代!码网

 mounted(){ this.getInfo() }

这样就可以在控制台中查看数据,以上是一个简单的get方法数据请求,下面继续介绍一下post方法的使用,其实post和get的使用没有什么区别只是再加上一个参数就可以了,看一下我们的代码

 methods:{ postInfo(){ let url = "url" let params=new URLSearchParams();//这个方法在axios的官网中有介绍,除了这个方法还有qs这个方法 params.append("key",index) params.append("key",index) axios.post(url,params).then((res)=>{ console.log(res) }) } }

同样在mounted这个生命周期中进行调用

 mounted(){ this.postInfo() }

补充:下面看下axios 数据请求

项目地址:https://github.com/axios/axios

axios是一个基于Promise,同时支持浏览器端和Node.js的HTTP库,常用于Ajax请求。

Vue.js 不像jQuery 或 AngularJS,本身并没有带Ajax方法,因此需要借助插件或第三方HTTP库。

GET和POST请求

 axios.get("./package.json",{ params:{ userId:"999" }, headers:{ token:"jack" } }).then(res=>{ this.msg = res.data; }).catch(function (error) { console.log("error init."+error) });

POST:

 <code class="language-javascript"> axios.post("./package.json",{ userId:"888" },{ headers:{ token:"tom" } }).then(res=>{ this.msg =res.data }).catch(err=>{ console.log(err) })</code>

基于Promise 可以执行多个并发请求:1

 function getUserAccount(){ return axios.get('/user/123') } function getUserPermissions(){ return axios.get('/user/12345/premissions') } axios.all([getUserAccount(),getUserPermissions()]) .then(axios.spread(function(acct,perms){ //请求都完时 }))

也可通过写入配置的形式发起请求:

 axios({ method:'post', url:'/user/123', data:{ firstName:'Fred', lastName:'Flintstone' } }).then(function(res){ console.log(res) })

在业务中经常将其封装为实例形式调用,便于通用配置:

 // util.js const instance = axios.create({ baseURL:"http://jsonplaceholder.typicode.com/", timeout:1000, headers:{"Content-Type":"application/x-www-form-urlencoded"} }) export default instance;

在mounted中调用:

 Ajax({ method:'post', url:'/package.json', data:{ firstName:'Fred', lastName:'flintone' } }).then(res=>{ console.log(res.data) this.msg = res.data })

强求拦截可用于loading..

 axios.interceptors.request.use(config=>{ console.log("require init"); return config }) axios.interceptors.response.use(response=>{ console.log("response init"); return response })

总结

以上就是vue axios数据请求get、post方法及实例详解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:vue axios数据请求get、post方法及实例详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址