vue ajax 回调,Vue的ajax请求

本文详细介绍了axios库的使用,包括GET和POST请求的两种方式,以及如何创建和配置请求实例。同时展示了并发请求的处理和响应类型设置。通过实例代码,解释了如何进行异步请求操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

axios基础请求

{{ site.name }}

new Vue({

el: '#app',

data: {

info: null,

},

methods: {

//get请求,lambda形式

getTest: function () {

axios

.get('../json/json_demo.json')

// .get('https://www.runoob.com/try/ajax/json_demo.json')

.then(response => { this.info=response.data.sites; })

.catch(error => { alert(error); });

},

//post请求,方法回调形式

postTest: function () {

axios

.post('/user', {

firstName: 'Fred', // 参数 firstName

lastName: 'Flintstone' // 参数 lastName

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

},

//可以通过向 axios 传递相关配置来创建请求

requestTest: function () {

axios({

method: 'post',

url: 'http://bit.ly/2mTM3nY',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

},

responseType: 'stream' //返回格式,例如图片

}).then(function (response) {

// response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))

})

},

//创建ajax实例,设置基础配置,搭配额外配置

ajaxTest: function () {

// 使用由库提供的配置的默认值来创建实例

// 此时超时配置的默认值是 `0`

const instance = axios.create({

baseURL: 'https://some-domain.com/api/',

timeout: 1000,

headers: {'X-Custom-Header': 'foobar'}

});

// 覆写库的超时默认值

// 现在,在超时前,所有请求都会等待 2.5 秒

instance.defaults.timeout = 2500;

// 为已知需要花费很长时间的请求覆写超时设置

instance.get('/12345',{

timeout: 5000

}).then(resp=>{}).catch(error=>{})

},

//axios同步请求(默认为异步请求)

async funA(){

var res = await axios.post('')//这里的res就是你axios请求回来的结果了

},

},

mounted: function () {

//执行多个并发请求

function getUserAccount() {

return axios.get('/user/12345');

}

function getUserPermissions() {

return axios.get('/user/12345/permissions');

}

axios.all([getUserAccount(), getUserPermissions()])

.then(axios.spread(function (acct, perms) {

// 两个请求现在都执行完成

}));

}

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值