vue中如何進(jìn)行異步請(qǐng)求
如何進(jìn)行異步請(qǐng)求
一、axios實(shí)現(xiàn)異步請(qǐng)求
1.項(xiàng)目中安裝axiox
npm install --save axios
2.在main.js中引入以供全局使用
import axios from 'axios' //可以給axios的ajax請(qǐng)求設(shè)置統(tǒng)一的主機(jī)和端口號(hào) axios.defaults.baseURL = "http://157.122.54.189:8080/"; //將axios這個(gè)對(duì)象添加到Vue的原型對(duì)象中,在使用的時(shí)候就只需要使用this.對(duì)象名就可以了 Vue.prototype.$http = axios
3.axios之get請(qǐng)求
vue前端:
<template> ?? ?<div> ?? ?</div> </template>
<script> export default { ? methods:{ ? ?? ?getData(){ ? ?? ??? ?//axios-get請(qǐng)求 ? ?? ??? ?this.$http.get('/getData1') ?? ? ? ? ? ?.then(r => console.log(r))//接口調(diào)用成功返回的數(shù)據(jù) ?? ? ? ? ? ?.catch(err => console.log(err)),//接口調(diào)用失敗返回的數(shù)據(jù) ? ? } ? } ? mounted(){//模板或el對(duì)應(yīng)的html渲染完成后再調(diào)用里面的方法 ?? ?this.getData() ? } } </script> <style lang="scss" scoped> ?? ? </style>
node后端:
server.get('/getData1',function(req,res){ res.send({ 'msg':'aaa' }) })
請(qǐng)求結(jié)果:
4.axios之post請(qǐng)求
Vue前端:
提交參數(shù)的兩種形態(tài):
// 1.可以直接傳入字符串 name=張三&age=19
// 2.可以以對(duì)象的形式傳入{name:“三”,age:19}
<template> ?? ?<div> ?? ?</div> </template>
<script> export default { ? methods:{ ? ?? ?getData(){ ? ?? ??? ?//axios-post請(qǐng)求傳值 ? ? ? 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對(duì)應(yīng)的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é)果:
看到這兒,你可能會(huì)疑惑,為什么post請(qǐng)求這么繁瑣。這和axios post方法默認(rèn)使用application/json格式編碼數(shù)據(jù)有關(guān),生成的數(shù)據(jù)格式是request payload,并不是我們常用的Form data格式(表單數(shù)據(jù)格式)。
使用這種編碼方式,傳遞到后臺(tái)的將是序列化后的json字符串,而不是我們想要的對(duì)象的形式,后端拿到的值則用原有的解析方式無法解析,則會(huì)解析出錯(cuò)誤的數(shù)據(jù)。故而,這里前端可以現(xiàn)將其轉(zhuǎn)化一下,轉(zhuǎn)化成鍵值對(duì)的形式再傳給后端,后端再稍作處理就可以正常使用。
當(dāng)然,也可以后端去做出解決,而且解決方式更加簡單一些,針對(duì)Node直接將傳過來的json字符串用body-parser中間件進(jìn)行解析就好。
server.post('/getData2',bodyParser.json(),function(req,res){ console.log(req.body); res.send({ 'msg':'bbb' }) });
二、vue-resource實(shí)現(xiàn)異步請(qǐng)求(和axios步驟基本相同)
1.項(xiàng)目中安裝vue-resource
npm install --save vue-resource
2.在main.js中引入以供全局使用
import vueResource from 'vue-resource' Vue.use(vueResource)//這兒有所不同
3.vue-resource之get請(qǐng)求
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請(qǐng)求
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請(qǐng)求
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ù),前端可以使用代理的方式,假裝是從同一域下請(qǐng)求的數(shù)據(jù),修改config下index文件,如下圖:
在最后調(diào)用的時(shí)候直接:
this.$http.get('/api/接口')
vue接口異步請(qǐng)求
// 查列表 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查列表的后幾項(xiàng) 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 { // 順序請(qǐng)求 await this.getSetupList(); await this.getRoleList(); await this.getList(); } catch (e) {} }
二:
getData: async function() { // 同步方法 try { // 順序請(qǐng)求 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é)果或進(jìn)行某些操作 }).catch(res => { reject('方法四返回錯(cuò)誤') }) }).catch(res => { reject('方法三返回錯(cuò)誤') }) }).catch(res => { reject('方法二返回錯(cuò)誤') }) }).catch(res => { reject('方法一返回錯(cuò)誤') }) }) }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實(shí)現(xiàn)移動(dòng)端可拖拽式icon圖標(biāo)
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)移動(dòng)端可拖拽式icon圖標(biāo),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03vue使用el-upload上傳文件及Feign服務(wù)間傳遞文件的方法
這篇文章主要介紹了vue使用el-upload上傳文件及Feign服務(wù)間傳遞文件的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03Element Cascader 級(jí)聯(lián)選擇器的使用示例
這篇文章主要介紹了Element Cascader 級(jí)聯(lián)選擇器的使用示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Vue基于Element-ui實(shí)現(xiàn)表格彈窗組件
這篇文章主要為大家詳細(xì)介紹了Vue基于Element-ui實(shí)現(xiàn)表格彈窗組件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04Vue proxyTable配置多個(gè)接口地址,解決跨域的問題
這篇文章主要介紹了Vue proxyTable配置多個(gè)接口地址,解決跨域的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-09-09vue內(nèi)嵌iframe跨域通信的實(shí)例代碼
這篇文章主要介紹了vue內(nèi)嵌iframe跨域通信,主要介紹了Vue組件中如何引入iframe,vue如何獲取iframe對(duì)象以及iframe內(nèi)的window對(duì)象,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì)需要的朋友可以參考下2022-11-11vue resource post請(qǐng)求時(shí)遇到的坑
這篇文章主要介紹了vue resource post請(qǐng)求時(shí)遇到的坑,需要的朋友可以參考下2017-10-10