vue中如何進行異步請求
如何進行異步請求
一、axios實現(xiàn)異步請求
1.項目中安裝axiox
npm install --save axios
2.在main.js中引入以供全局使用
import axios from 'axios' //可以給axios的ajax請求設置統(tǒng)一的主機和端口號 axios.defaults.baseURL = "http://157.122.54.189:8080/"; //將axios這個對象添加到Vue的原型對象中,在使用的時候就只需要使用this.對象名就可以了 Vue.prototype.$http = axios
3.axios之get請求
vue前端:
<template> ?? ?<div> ?? ?</div> </template>
<script>
export default {
? methods:{
? ?? ?getData(){
? ?? ??? ?//axios-get請求
? ?? ??? ?this.$http.get('/getData1')
?? ? ? ? ? ?.then(r => console.log(r))//接口調(diào)用成功返回的數(shù)據(jù)
?? ? ? ? ? ?.catch(err => console.log(err)),//接口調(diào)用失敗返回的數(shù)據(jù)
? ? }
? }
? mounted(){//模板或el對應的html渲染完成后再調(diào)用里面的方法
?? ?this.getData()
? }
}
</script>
<style lang="scss" scoped>
?? ?
</style>node后端:
server.get('/getData1',function(req,res){
res.send({
'msg':'aaa'
})
})請求結(jié)果:

4.axios之post請求
Vue前端:
提交參數(shù)的兩種形態(tài):
// 1.可以直接傳入字符串 name=張三&age=19
// 2.可以以對象的形式傳入{name:“三”,age:19}
<template> ?? ?<div> ?? ?</div> </template>
<script>
export default {
? methods:{
? ?? ?getData(){
? ?? ??? ?//axios-post請求傳值
? ? ? this.$http({
? ? ? ? ? method:"post",
? ? ? ? ? url:"/getData2",
? ? ? ? ? headers:{
? ? ? ? ? ? ? 'Content-type': 'application/x-www-form-urlencoded'
? ? ? ? ? },
? ? ? ? ? data:{
? ? ? ? ? ? ? name:'xxx'
? ? ? ? ? },
? ? ? ? ? transformRequest: [function (data) {//更改傳值格式
? ? ? ? ? ? ? let ret = ''
? ? ? ? ? ? ? for (let it in data) {
? ? ? ? ? ? ? ? ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
? ? ? ? ? ? ? }
? ? ? ? ? ? ? return ret.slice(0,ret.length-1)
? ? ? ? ? ? }],
? ? ? })
? ? ? ? .then(r => console.log(r))
? ? ? ? .catch(err => console.log(err))
? ? }
? }
? mounted(){//模板或el對應的html渲染完成后再調(diào)用里面的方法
?? ?this.getData()
? }
}
</script>
<style lang="scss" scoped>
?? ?
</style>node后端:
server.post('/getData2',function(req,res){
req.on("data",function(data){
console.log(querystring.parse(decodeURIComponent(data)));
});
res.send({
'msg':'bbb'
})
})結(jié)果:


看到這兒,你可能會疑惑,為什么post請求這么繁瑣。這和axios post方法默認使用application/json格式編碼數(shù)據(jù)有關,生成的數(shù)據(jù)格式是request payload,并不是我們常用的Form data格式(表單數(shù)據(jù)格式)。
使用這種編碼方式,傳遞到后臺的將是序列化后的json字符串,而不是我們想要的對象的形式,后端拿到的值則用原有的解析方式無法解析,則會解析出錯誤的數(shù)據(jù)。故而,這里前端可以現(xiàn)將其轉(zhuǎn)化一下,轉(zhuǎn)化成鍵值對的形式再傳給后端,后端再稍作處理就可以正常使用。
當然,也可以后端去做出解決,而且解決方式更加簡單一些,針對Node直接將傳過來的json字符串用body-parser中間件進行解析就好。
server.post('/getData2',bodyParser.json(),function(req,res){
console.log(req.body);
res.send({
'msg':'bbb'
})
});二、vue-resource實現(xiàn)異步請求(和axios步驟基本相同)
1.項目中安裝vue-resource
npm install --save vue-resource
2.在main.js中引入以供全局使用
import vueResource from 'vue-resource' Vue.use(vueResource)//這兒有所不同
3.vue-resource之get請求
this.$http.get('/getData1')
.then(r => console.log(r))//接口調(diào)用成功返回的數(shù)據(jù)
.catch(err => console.log(err)),//接口調(diào)用失敗返回的數(shù)據(jù)4.vue-resource之post請求
this.$http.post('/getData2',{name:"bbb"})
.then(r => console.log(r))//接口調(diào)用成功返回的數(shù)據(jù)
.catch(err => console.log(err)),//接口調(diào)用失敗返回的數(shù)據(jù)5.vue-resource之jsonp請求
this.$http.jsonp('/getData3')
.then(r => console.log(r))//接口調(diào)用成功返回的數(shù)據(jù)
.catch(err => console.log(err)),//接口調(diào)用失敗返回的數(shù)據(jù)注意
如果在使用jsonp之后還是無法獲取到跨域的數(shù)據(jù),前端可以使用代理的方式,假裝是從同一域下請求的數(shù)據(jù),修改config下index文件,如下圖:

在最后調(diào)用的時候直接:
this.$http.get('/api/接口')vue接口異步請求
// 查列表
async getlist (pageIndex) {
let data = {
pageIndex,
pageSize: this.pageSize
}
await getCouponPageList(data).then(res => {
const { data: { code, msg, data } } = res
if (code === 0) {
data.list.forEach(v => {
v.totalAmount = ''
v.buyerPayAmount = ''
})
this.tableData = data.list
data.list.forEach(async (ele, index) => {
if (ele.status === this.$t('已使用')) {
let temp = await this.couponGetAlipay(ele.billDetails)
ele.totalAmount = temp.totalAmount / 100
this.tableData[index] = ele
}
})
this.dataCount = data.total
} else {
this.$Message.error(msg)
}
this.loading = false
}).catch(err => {
console.log(err.message)
})
},
// 根據(jù)id查列表的后幾項
couponGetAlipay (orderNo) {
return new Promise((resolve, reject) => {
couponGetAlipay({orderNo}).then(res => {
const { data: { code, data } } = res
if (code === 0) {
resolve(data)
}
}).catch(err => {
console.log(err.message)
})
})
},


其他方法
一:
getData: async function() { // 同步方法
try { // 順序請求
await this.getSetupList();
await this.getRoleList();
await this.getList();
} catch (e) {}
}二:
getData: async function() { // 同步方法
try { // 順序請求
await this.getSetupList();
await this.getRoleList();
await this.getList();
} catch (e) {}
}
三:
function login(code) {
return new Promise((resolve, reject) => { // 同步方法
getData1().then(response => { // 方法一
return response // 返回正確值
}).then((res) => {
getData2().then((response) => { // 方法一返回正確后執(zhí)行方法二
return response // 返回正確值
}).then((res) => {
getData3().then(response => { // 方法二返回正確后執(zhí)行方法三
return response // 返回正確值
}).then(res => {
getData4().then(response => { // 方法三返回正確后執(zhí)行方法四
resolve(response ) // 方法執(zhí)行完畢,拋出最后結(jié)果或進行某些操作
}).catch(res => {
reject('方法四返回錯誤')
})
}).catch(res => {
reject('方法三返回錯誤')
})
}).catch(res => {
reject('方法二返回錯誤')
})
}).catch(res => {
reject('方法一返回錯誤')
})
})
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue使用el-upload上傳文件及Feign服務間傳遞文件的方法
這篇文章主要介紹了vue使用el-upload上傳文件及Feign服務間傳遞文件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03
Element Cascader 級聯(lián)選擇器的使用示例
這篇文章主要介紹了Element Cascader 級聯(lián)選擇器的使用示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07
Vue proxyTable配置多個接口地址,解決跨域的問題
這篇文章主要介紹了Vue proxyTable配置多個接口地址,解決跨域的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

