Vue 3.0 Computed

Posted on  by admin

In October 2019, Vue 3.0 pre-alpha was finally released. So it’s the matter of time to use Vue 3.0 as production.

Replace Vue 2.0 “methods” !

To prepare for it, I would like to share how to migrate from Vue 2.0 to Vue 3.0. Because these days large amount of Vue users has already introduced TypeScript, this article also use TypeScript.

There are 3 steps on the migration like below. Because the topic is bit long, I splitted it into 3 articles. This article is the continuation of the first step. If you want to start from the specific part, feel free to proceed to the page.

You already setup Vue 3.0 composition API in the previous article!

Props

So Let’s replace Vue 2.0 code with Vue 3.0 gradually !

In Vue 2.0, “Vue.extend” is used to let TypeScript properly infer types inside Vue component.

Instead of “Vue.extend”, you must use createComponent in Vue 3.0 for type inference.

In addition, inside of createComponent, you should use setup function which is an entry point where composition functions are invoked. But when you replace Vue.extend to createComponent, you have many errors in your editor because createComponent doesn’t know this in Vue 2.0.

You have many compile errors in the terminal. But Don’t worry. This error is from Vetur. Everything works fine. Next step is replacing local state of Vue 2.0, data .

It’s super simple, use reactive inside of setup function like below. reactive is the equivalent of the current Vue.observable() in Vue 2.0.

Emit

Returned value from reactive is a reactive object which you like. Actually, you have different API to make variables reactive called ref() . But the function itself is pretty similar to reactive(). Please check the official documentation for it. Methods in Vue2.0 become simple functions inside setup function.

It’s easier to see the codes.

Let’s get todos first.

Because you don’t have to use this to access local state, it’s simpler. So far, you have the function to initialize todos. But when do you call it ? Yes, you want to do it when Vue instance is “Mounted”. Of course Vue 3.0 has lifecycle hooks.

You should use it like below. You can move rest of methods to inside setup function.

After moving all method, List.vue becomes like below.
One thing you don’t know yet is, two arguments of setup, props and context. Props is easy to understand.