首页 > 解决方案 > 如何避免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) => {
})
}

标签: javascriptvue.jsionic-frameworkvuejs3

解决方案


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 selectedvariable.

例如,如果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()"

在此处了解有关观察者的更多信息


推荐阅读