Home > Net >  Use of loadash debounce method in Vue3 with Composition API
Use of loadash debounce method in Vue3 with Composition API

Time:08-13

I am converting some of my Vue2 code with Option API to Vue3 Composition API and having difficulty with loadash's debouce method-

Code that works in Vue2 Option API:

onSearch(search, loading) {
    if(search.length > 3) {
        loading(true);
        this.search(loading, search, this);
    }
},
search: _.debounce((loading, search, vm) => {
    axios.get(`example_endpoint?q=${escape(search)}`).then(res => {         
        (vm.dummy_data = res.data.data);
        loading(false);
    });

}, 350),

I tried the following in composition API but it would not work:

const dummy_data = ref([]);

function onSearch(search, loading) {
   if(search.length > 3) {
      _.debounce((search, loading) => {
        axios.get(`example_endpoint?q=${escape(search)}`).then(res => {         
            dummy_data.value = res.data.data;
            loading(false);
        });
      }, 250);
   }
}

Note: It is used for AJAX search in the Vue-Select component.

<v-select taggable push-tags 
    
    label="name" 
    :filterable="false" 
    :options="dummy_data" 
    @search="onSearch" 
</v-select>

CodePudding user response:

Refs are generic objects. You need to write a value to it, no overate whole object.

dummy_data.value = res.data.data;

You should have warning Cannot assign to 'dummy_data' becouse it is a constant. Check your extensions i use Volar for Nuxt 3 with Vue 3.

CodePudding user response:

Debounce can't correctly work correctly if it's defined in the place that is supposed to be called. The result of _.debounce(...) is a function, it's not called here. It should follow the same structure as original code:

const search = _.debounce((searchValue, loading) => {...}, 250);

function onSearch(searchValue, loading) {
   if(searchValue.length > 3)
     loading(true);
     search(searchValue, loading);
}
  • Related