简体   繁体   English

如何在 Vue 3 Composition API 中的手表 function 中使用处理程序 _.throttle function?

[英]How can I use handler _.throttle function within watch function in Vue 3 Composition API?

I have a reactive data object, filters .我有一个反应数据 object, filters I need to watch for changes, whenever there is an update.每当有更新时,我都需要注意变化。 I was successful to do so within Options API.我在选项 API 中成功地做到了这一点。 But in the below use case, unable to make it work with Composition API.但在以下用例中,无法使其与 Composition API 一起使用。 Here is the code piece below, please help me to convert it, so that its compatible with the setup() syntax.这是下面的代码片段,请帮我转换它,使其与setup()语法兼容。 Please help me here.请在这里帮助我。

filters: {
    handler: _.throttle(function() {
        let query = _.pickBy(this.filters);
        let route = this.route('users.index', Object.keys(query).length ? query : {
            remember: 'forget'
        });
        this.$inertia.get(route, {}, {
            only: ['usersData'],
            preserveState: true,
            preserveScroll: true
        });
    }, 300),
    deep: true,
},

I am able to format it according to the syntax required for Composition API, but unable to _.throttle, how can I format the above so that it works the same way with the Composition API?我能够根据合成 API 所需的语法对其进行格式化,但无法 _.throttle,我该如何格式化上述内容,以便它与合成 API 以相同的方式工作? This is what I am doing right now, to log the response.这就是我现在正在做的,记录响应。 But need to wrap the whole function within _.throttle.但需要将整个 function 包裹在 _.throttle 中。

watch(() => _.pickBy(filters), (currentValue, oldValue) => {
    console.log(currentValue);
    console.log(oldValue);
})

As the solution was not shared, here is a working example.由于未共享解决方案,因此这是一个工作示例。

import { watch } from "vue";
import { Inertia } from "@inertiajs/inertia";
import pickBy from "lodash/pickBy";
import throttle from "lodash/throttle";

Watch手表

watch(
  () => filters,
  throttle(() => {
    Inertia.get(route("users.index"), pickBy(filters), {
      preserveState: true,
    });
  }, 300),
  { deep: true }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM