Skip to content
Advertisement

Property or method “_” is not defined on the instance but referenced during render

Im a capable react developer, but have inherited a vue.js project from another developer and have maintained it for several years now, unfortunately I haven’t gone through much personal effort to learn vue as i should.

I have a strange error being thrown from using lodash, I believe it doesnt like my _.debounce call

Component:
JavaScript
console.error
JavaScript

Advertisement

Answer

Accessing _ in template

Assuming you’re using the Options API, importing _ does not automatically make it available to the template (as @tao pointed out in his answer). The template can only access fields exposed via the component options (e.g., data, props, methods, computed, etc.) in addition to a few allow-listed globals (Vue 2 allowed globals, Vue 3 allowed globals).

Using _.debounce

_.debounce‘s first argument is a function reference:

JavaScript

To create a debounced submit, pass the submit-reference as an argument to _.debounce like this:

JavaScript

You technically could invoke the debounced function immediately:

JavaScript

…but don’t do that in the template (see reason below).

Using a debounced event handler for v-on

When the value of the v-on directive (@ for shorthand) is an expression (as in your case), the template compiler automatically wraps the expression in a function, so this:

JavaScript

…essentially becomes:

JavaScript

…which would have no effect, since debounce doesn’t invoke the wrapped function itself.

You might be tempted to call the function immmediately in:

JavaScript

…but that creates a new debounced function on every event, which defeats the debouncing.

Solution

Create a debounced function in the <script> part of the SFC that could then be used as the v-on value:

Options API:

JavaScript

Composition API in setup() option:

JavaScript

Composition API in <script setup>:

JavaScript

Template:

JavaScript

demo

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement