javascript - 如何避免vue中api调用的onchange?
问题描述
我有使用选择选项的代码。在更改选项时,我正在提交一个 API 请求,它将数据发送到服务器。当我加载组件时,我选择了已为该 onmount 组件选择的选项,我发送 api 请求并将已选择的值分配给变量selected
。现在的问题是当我将值分配给选择选项时,选择检测该值已更改,因此它在页面加载时提交请求。这是不需要的,它应该只在用户更改选项时发送请求
这是选择 html
<ion-select interface="popover" multiple="true" v-model="selected" :value="selected" style="min-height: 90px;white-space: normal;" @ionChange="submitWorkerArrival()">
<ion-select-option v-for="(worker, index) in workers" :key="index" v-bind:value="worker.id">{{worker.name}}</ion-select-option>
</ion-select>
这是我将值分配给selected
变量的获取请求
ApiService.get(url).then((response) => {
this.workers = response.data.workers;
this.selected = Object.values([...new Set(response.data.arrived_workers)]);
});
这是提交请求,我在更改时提交
submitWorkerArrival() {
ApiService.post(url, data).then(async (res) => {
})
}
解决方案
I would add a watch to selected
, this way when selection changes you are able to add additional logic based off of the previous state of the selected
variable.
例如,如果selected
是 null 但现在不是,您知道您的代码已经加载了以前的值,因此无需向您的 API 发送请求。
watch:{
selected:{
handler(newVal, oldVal)
{
if(!oldVal) return; //prevent first load from firing event
//Replace prop with a property that would change
if(newVal.prop !== oldVal.prop){
this.submitWorkerArrival();
}
},
deep: true //important to watch object for changes
}
}
然后你会删除
@ionChange="submitWorkerArrival()"
在此处了解有关观察者的更多信息
推荐阅读
- .net - 无法读取配置部分“system.web.extensions”,因为它缺少部分声明(发生在特定的代码分支上)
- javascript - 使用 Ajax 更改单击按钮的状态
- sql - 我需要列表中以“b”开头的序列,下一个值是 SQL Server 查询中的“e”,并消除所有其他
- angular6 - 如何使用回调函数和常规函数返回值
- flynn - 如果发现令牌未知,如何将新主机添加到 flynn?
- python - 如何从不带参数 discord.py 的命令中获取服务器对象
- javascript - 可以将繁琐的连接和请求事件侦听器放在 Node.js 的单独模块中吗?
- python-3.x - pytesseract 无法识别图像中的字符
- asynchronous - 出站 ChannelHandler 的包罗万象的异常处理
- google-drive-api - GoogleDrive API 策略限制导出下载 10 mb