Skip to content
Advertisement

How to define variable in vue template?

Problem

I have the need to temporarily store the results of a method call in Vue templates. This is particularly common inside loops, where I cannot easily use computed properties.

JavaScript

Javascript snippet:

JavaScript

To improve performance, I really need a variable to store the method call result.

What is the Vue way to solve this problem?

Advertisement

Answer

A quick way to work around Vue’s current shortcomings is to use scoping through v-for and a single loop. A hopefully explanatory example:

JavaScript

The <template> element above does the trick. You call your function (someFunction) in a temporary size-1 array of objects, assign it to a property (isLocked), which in turn is assigned to a scoped variable (scope). You can now access whatever someFunction returns as many times as you like without sacrificing performance through scope.isLocked.

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