Home » vue » Use data value for lodash.throttle timeout in vue.js SFC

Use data value for lodash.throttle timeout in vue.js SFC

Posted by: admin November 26, 2021 Leave a comment

Questions:

Hey to all people here,

I am fairly new to Vue.js but I think I start getting in to it. However, I have a problem with my Single File Components in combination with lodashs throttle() function. Here is what my component looks so far:

<template>
    <fieldset class="fieldset-shorttext">
        <label v-bind:for="itemId"
               v-text="label"></label>
        <input v-bind:name="itemId"
               v-bind:id="itemId"
               v-model="input"
               type="text" />
    </fieldset>
</template>

<script>
    import _ from 'lodash'

    export default {
        data() {
            return {
                itemId: '123450',
                label: 'Test Label',
                input: 'Test value',
                throttled: 200
            };
        },
        watch: {
            input: function (value) {
                this.throttledValuePush(value)
            }
        },
        methods: {
            throttledValuePush: _.throttle(function(value) {
                console.log(value);
            }, this.throttled)
        }
    };
</script>

<style>
    .fieldset-shorttext {
        border:0;
    }
</style>

When I run this in my browser I get an error that this.throttled (used as the timeout parameter for my throttle() function) is not defined. It works when I use a fixed value such as 200 for example. But I can’t get it running by using the value of the “throttled” data variable.

Can anyone help me? Thank you very much in advance.

EDIT: I added a sandbox example here: https://codesandbox.io/s/434490z5v9

Answers:

The data object is instantiated and its properties put into this after methods, you cannot use this.throttle at that time.

Instead, You can use this.throttl in the mounted lifecycle hook

methods: {
    throttledValuePush: undefined,
},
mounted() {
    this.throttledValuePush = _.throttle((value) => console.log(value), this.throttled);
}