【问题标题】:how to avoid onchange on api call in vue?如何避免vue中api调用的onchange?
【发布时间】:2021-10-04 10:40:16
【问题描述】:

我有使用选择选项的代码。在更改选项时,我正在提交一个 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变量赋值的get请求

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) => {
})
}

【问题讨论】:

  • 可以在worker.id上做一个watch

标签: javascript vue.js ionic-framework vuejs3


【解决方案1】:

我会在@ 987654322中添加手表,以这种方式在选择变化时,您可以基于selected变量的先前状态添加其他逻辑。

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

在此处了解有关watchers 的更多信息

【讨论】:

    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2018-07-18
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多