我有一個發出值的子組件,并且在父組件中,每次發出該值時,我都會使用該值執行 axios 呼叫。我的問題是,只有在 x 毫秒(或秒)內孩子沒有發出另一個值以減少我做的呼叫量時,我才想觸發 axios 呼叫。
代碼在這里:
<script>
import axios from "axios";
import DataTable from './DataTable.vue';
export default {
name: 'Test',
data() {
return {
gamertags: [],
// Utils
timeout: 500,
delay: 500
}
},
methods: {
// API calls
async getGamerTags(string='') {
const path = `http://localhost:5000/gamertags?string=${string}`
await axios.get(path)
.then((res) => {
this.gamertags = res.data;
})
.catch((error) => {
console.error(error);
});
},
// DataTable
handleFilters(filters) {
clearTimeout(this.timeout);
this.timeout = setTimeout(this.getGamerTags(filters.find(o => o.field == "playerGamerTag").filter), this.delay);
}
}
components: {
DataTable
}
};
</script>
<template>
<DataTable
@filters="handleFilters"
/>
</template>
提前致謝。
uj5u.com熱心網友回復:
你需要的是去抖動。這是一個例子:
var timeout, delay = 3000;
function func1() {
clearTimeout(timeout);
timeout = setTimeout(function(){
alert("3000 ms inactivity");
}, delay);
}
<input type="text" oninput="func1()">
發射時,只需呼叫func1(),如果 3000 毫秒后沒有新的發射,將執行超時函式。
uj5u.com熱心網友回復:
如果您也添加代碼,最好理解問題和用例。但據我所知,這是兩種方式
- 如果您使用內部輸入和基于觸發的
@changed事件,您可以@change.lazy在每次更改時添加此不觸發。 - 第二種解決方案是
setTimeout(function,delayInMs)在父級內部使用
vuejs 檔案鏈接
uj5u.com熱心網友回復:
只需將handleFilters函式更改為:
handleFilters(filters) {
clearTimeout(this.timeout);
this.timeout = setTimeout(
this.getGamerTags,
this.delay,
filters.find(o => o.field == "playerGamerTag").filter
);
},
問題已經解決了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472644.html
