vue中循環(huán)請求接口參數問題及解決
vue 循環(huán)請求接口參數問題
今天遇到一個循環(huán)請求問題
先上代碼
function(){ ? ? ? var num = this.eventType.length; ? ? ? for (var i = 0; i < num; i++) { ? ? ? ? arr.eventType = this.eventType[i]; ? ? ? ? console.log(arr.eventType, i, "arr"); ? ? ? ? this.getChart(arr); ? ? ? ? this.getPie(arr); ? ? ? } } ? ? getChart(arr) { ? ? //接口請求 ? ? }, ? ? getPie(arr) { ? ? //接口請求 ? ? },
問題出在eventype上,在接口請求前打印出的eventype都是不一樣的,在接口里面打印,每次都是一樣的,這導致每次接口的請求參數都是一樣,獲取的數據也是一樣。
搞了半天才找到原因,修改如下
async function(){ ? ? ? var num = this.eventType.length; ? ? ? for (var i = 0; i < num; i++) { ? ? ? ? arr.eventType = this.eventType[i]; ? ? ? ? console.log(arr.eventType, i, "arr"); ? ? ? ? await this.getChart(arr); ? ? ? ? await this.getPie(arr); ? ? ? } } ? ? async getChart(arr) { ? ? await //接口請求 ? ? }, ? ? async getPie(arr) { ? ? await //接口請求 ? ? },
這下就ok了。
原因在于async是同步請求,每次循環(huán)都會執(zhí)行請求
vue for循環(huán)請求同一url參數不同但參數覆蓋
今天搞Vue 遇到一個比較怪異的問題,看代碼
let self=this for (let i = 0; i < data.length; i++) { ? ? ? ? ? ? ? ? let item = data[i] ? ? ? ? ? ? ? ? item['id'] = i + 1// 賦值序號 ? ? ? ? ? ? ? ? item['similarity'] = parseFloat(item['similarity']).toFixed(2) ? ? ? ? ? ? ? ? // } ? ? ? ? ? ? ? ? this.resembleData = data ? ? ? ? ? ? ? ? // 分次請求軌跡數據 ? ? ? ? ? ? ? ? let targetIdParam = item['targetId'] ? ? ? ? ? ? ? ? self.queryTrajParams['targetId'] = targetIdParam ? ? ? ? ? ? ? ? self.queryTrajParams['sourceId'] = null ? ? ? ? ? ? ? ? console.log('targetId參數', targetIdParam) ? ? ? ? ? ? ? ? console.log('queryTrajParams', self.queryTrajParams) ? ? ? ? ? ? ? ? axios.get(serviceUrl.trajectoryDataUrl, { ? ? ? ? ? ? ? ? ? params: self.queryTrajParams ? ? ? ? ? ? ? ? }).then(res => {
....省略
發(fā)現network請求的url參數同一個,而且都是最后一個,看來是參數被覆蓋了,我是Java出身,碰到這種問題一臉懵逼
是一枚前端小菜雞,不過我隱約發(fā)現是參數的類型原因,然后我試了下基本數據類型,只傳number類型,果然能傳成功
看來就是對self.queryTrajParams進行一下轉換
?let queryParam = JSON.parse(JSON.stringify(self.queryTrajParams))
使用let 對參數進行重定義,let會生成一份臨時傀儡代碼塊,每次都會生成!!
axios.get(serviceUrl.trajectoryDataUrl, { ? ? ? ? ? ? ? ? ? params: queryParam? ? ? ? ? ? ? ? ? }).then(res => {
然后完美解決問題??!
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue.js 使用v-if v-else發(fā)現沒有執(zhí)行解決辦法
這篇文章主要介紹了vue.js 使用v-if v-else發(fā)現沒有執(zhí)行解決辦法的相關資料,需要的朋友可以參考下2017-05-05vue3?element-plus?實現表格數據更改功能詳細步驟
這篇文章主要介紹了vue3 element-plus實現表格數據更改功能,本文分步驟結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07使用form-create動態(tài)生成vue自定義組件和嵌套表單組件
這篇文章主要介紹了使用form-create動態(tài)生成vue自定義組件和嵌套表單組件,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01