您的位置:首页 > Web前端 > Vue.js

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

2018-09-11 15:21 971 查看

我们常用的有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这个生命周期中进行调用

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方法及实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue axios 数据 请求 get post