Vue 3.0 Ref

Posted on  by admin
With the current Vue 2.x way of building components, we’re separating it by the option, not feature.

What this means is that for example, a single toggling state for showTitlewill need to have reactive data in data()and a methodto toggle the state.

For a small simple component, this won’t be a problem.

But as the component grows, more functionality will be added, thus making reading the whole feature more difficult. An example can be seen below. Now that might still be readable to some extent, but as you can see we started to get different concerns of functionality split by dataand methods.

This will continue to get more complex when the component grows, let alone if we need to add computedor lifecycle hooks.

Now on Vue 2.x, we have mixinsthat can address this concern.

const user = reactive({ ...props.apiUser });

Mixins can be used for functionality purposes, making related data end methods in one file, then importing that file wherever it needed.

We’ll need to open the file, read again and when finished, check other places that use it making sure none of them broke. Other things are that there is a great potential that mixins can have similar names, which will make various issues.

The upcoming Composition API is the solution Vue 3 introduces to resolve the above issues.

At the moment of writing (May 2020) it is still in beta, but we can already try it. It can make related data, methods, and functions scoped in one place instead of spread all over the file.

We can use it in existing Vue 2.x projects by installing an additional npm package. Afterward, we will need to import the package in our app.jsfile as we can see below. If you are starting from scratch with Vue 3.0 however, we can directly import everything in a .vue file from vue.

We can now access the setup() function inside our .vue file.

This function will run on component initialization, acts as a replacement to beforeCreate and created lifecycle hooks.

Now let’s see how we can use some of this enhancement compared to existing Options API in the previous Vue version.

Reactivity is the main advantage when using Front End Javascript framework like Vue.

How Vue.js refs work