简体   繁体   中英

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

I have a reactive data object, filters . I need to watch for changes, whenever there is an update. I was successful to do so within Options API. But in the below use case, unable to make it work with Composition API. Here is the code piece below, please help me to convert it, so that its compatible with the setup() syntax. 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? This is what I am doing right now, to log the response. But need to wrap the whole function within _.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 }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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