A setup function with Vue 2.x

Jelle Hak
2 min readMay 18, 2021

The official vue documentation tells you to put your methods in an object methods. This sounds quite logic, but wait here a moment. Is it really that handy? We have no shared scope between the methods besides this. Problem is that most IDE not understanding what this would be and could therefor not give you any linting aid.

So what is the alternative? Write your methods in the created lifecycle. And use this with caution. This is a similar approach to the new setup function in Vue 3. See below an example.

Example

Tip: You can also write your watch methods in the created lifecycle with this.$watch

Better performance

Using the created function to specify all you methods lets you utilise a shared scope. This can be a big performance boost when using external library. For example if you are using a big library like ‘Google maps’ or ‘ThreeJs’ it would be common to bind it to you data to have it accessible in your methods. Yet this implies a major penalty as Vue will add recursively ‘Reactivity’ ( getters and setters ) to all the properties of the object. Using it in the created function makes sure Vue doesn’t get grip of the object and therefor not add the Reactivity to it. If you desire reactivity you could still bind parts of it to the data section.

For performance sake of your clients make sure to see if reactivity has slipped through, easiest to test is to do a console.log and check your developer inspector. You can then check if the object has or hasn’t got the setters and getters attached.

Pitfalls

There is one minor pitfall I came across with this approach: You should bind the methods before running any async code inside your created method.

Conclusion

If you still use Vue 2.x and wish to move over to Vue 3 some time it’s good to rewrite your app to have the methods in the created function. This will make a switch to Vue 3 easier. Also if you have written an app / plugin for Vue 2.x it would be good to make sure you aren’t polluting big objects with reactivity, if so move your methods to the created function.

--

--