Vue2 the Vue3 way: Getting Started

Or Perlman
The Zeals Tech Blog
10 min readDec 9, 2021
Vue Logo

Introduction

My name is Or Perlman, a tech-lead for the mobility division at Zeals.
We are a SaaS company based in Tokyo, that aims to provide chatbot experience through b2c.

In my career, I have been a software and web engineer for the past 14+ years (You can find me on LinkedIn).

On a day-to-day basis, other than my technical lead duties I am also the frontend leader for my team.

For those of you who are new to this series, you are welcome to go back to part 1 (link below) and read about the background for this series and how we have decided to use Vue.

On the mobility team we are currently using Vue to build out our CRM system for business members and clients.

In this article I would like to cover a few goals:

  • Have you setup your environment in Vue2 using Vue-CLI.
  • Cover briefly the basics behind creating components in Vue2.
  • Explain what is Composition-API and how to use it.
  • Convert the generated project code from Options-API to Composition-API.

Series Breakdown

  • Why a new Framework?: Background behind why we decided to pursue a new framework and why that framework is Vue.
  • Getting Started: Covering how to get started with Vue2 and how we can convert our Options API component to Composition API.
  • Login Form: We will go over converting our simple component to a Login form, while continuing to use Composition API and adding Pinia (state management).
  • Testing: We will cover how to add validations using VeeValidate and unit testing with Jest.
  • What is next: Summary and a look at what the future holds (Script setup).

As the time of this writing it is possible that the sections above may change (either shorten or increase, depending on the amount of information per part).

Introduction

If this is your first time coming to Vue, you can refer to the wonderful documentation from the Vue core team, follow some tutorials or watch some courses on YouTube to get you started (While requiring a subscription, I can recommend this wonderful course by Sarah Drasner from the frontendmasters website).

As the title of the article mentions, we will focus on Vue2 in this article.

I will make a few assumptions in this article that will be important for you to follow my explanations.

Prerequisites

  1. You have used some sort of frontend framework in the past or at least familiar with the concepts behind them.
  2. You heard about Vue and at least familiar with what it is suppose to represent.
  3. You have NodeJS installed (my current local version is v14.17.6).
  4. You have Yarn V1 installed globally.
  5. You are using VSCode.

(Optional) There may be cases where I will refer to OS related commands. For my development environment I am using Ubuntu using WSL2 on Windows, but you can search for alternative commands on your favorite distribution.

Scaffolding our Project

To get started quickly we will be using the wonderful Vue-CLI package to create our base project (for those coming from React, this is similar in a way to the create-react-app project).

Run yarn global add @vue/cli from your terminal to install Vue-CLI in your environment.

Decide on a location where you would like to create your project and run vue create vue2-the-vue3-way .

The CLI will present you with a multi-choice menu.
Since our focus in this article is not Vue CLI we will be going with the default Vue2 setting (The Vue-CLI documentation goes more in-depth with each option).

VUE CLI Multi Menu

Once the CLI is finished with creating the project, we will redirect our terminal to point to our newly created project by running the command cd vue2-the-vue3-way .

Our project is not created with Typescript support by default (this is an option if we had selected to customize our CLI project creation), so instead, we will be adding it by running vue add typescript.

When prompted by the CLI to answer some questions, please use the answers below.

Vue CLI Typescript Support Options

Finally, to confirm that the project is working correctly, we can run yarn serve .

Unfortunately Medium doesn’t allow pictures resizing, so the webpage picture is not included

Before we dive in to the core of the article regarding the Vue3 approach (Composition-API), I would like to go over some of the Vue2 concepts, so you would have a better understanding of what approaches are used in Vue2 and how they are changing in Vue3.

Important to note that this is by no means meant to be an in-depth beginner’s guide to Vue2 or Vue3. The review below is only meant as a brief background into what the framework has to offer.

Vue2: Directives

For those who are coming from Angular, Directives in Vue will be very familiar. To quote Evan You, “ I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight.”

Directives can be thoughts of as actions/methods that can be called from a template, whether it is to hide/not-render a property (v-show, v-if), define 2-way binding for a property (v-model) or loop over data (v-for).

Vue2: Options API/Class Component

Options API

The Options API is the default syntax in Vue2 on how to create a component.
The syntax is considered to be simple by separating the various sections of the component into functions.

  • Data: A section to define the data that will be shared with the template (view).
  • Props: A section to define the properties that are exposed when wanting to implement the component in another component.
  • Computed: This is a concept that is more than a one-liner (Vue even has its own documentation for it), but if to try to summarize it is, we can think of an option that Vue provides us to cache certain operations (For those who are coming from Angular, you can think of it as a cached version of pipes. For those who are using state management, you can try to think of it as something similar to selectors/getters).
  • Methods: A section to define the methods that we will be wanting to call from our template.
  • Watch: A section to define properties that can be tracked (what was the value before and what changed).

In the following code sample I have taken the default HelloWorld component (you can find it in your project directory under src/components/HelloWorld.vue) and modified it to meet the following criteria’s:

  1. The component should be able to receive a name when being called from a separate component (props usage).
  2. The component will show by default a welcoming message (data usage).
  3. The user can update the welcoming message (watch usage).
  4. The user keyboard input should be logged into the browser console (methods usage).
A simple example of how to update a message and display it using features from Options API

Class Components

The Class component approach is a project created by the community to offer an alternative syntax to the Options API that adopts a more object-oriented approach with Typescript support (For those who are coming from Angular, the syntax is almost identical using decorators and ES6 syntax).

While not an official package from the core team (you won’t find any documentation about it on the Vue official website), it has been recognized and recommended by the core team, even being included as an option in the Vue-CLI.

In some cases, you may come across libraries in the Vue2 ecosystem that will even have code examples that use the Class component syntax as if it is the default approach for creating components.

The following is a code sample based on the example above for Options API, written using the Class Component syntax to allow us to show and alter a message, including showing a name we receive as a parameter.

A simple example of how to update a message and display it using features from Class Component

Vue2: Plugins

Before moving to discuss Composition-API, there is another concept that is worth reviewing and that is plugins.

Plugins are a concept in Vue2 of introducing a global (singleton) feature that could be used by every single component.

Vue2 comes with pre-built-in plugins in the form of Instance Properties and Instance methods.

External Libraries will in most cases be also used as plugins.
For example, the Vue Router ($router/$route) or Vue i18n ($t).

You can access plugins directly from a component using this keyword.
Plugins are also accessible directly from the template by referencing them directly (For example, $refor $t ).

Vue3: Composition-API/Reactivity

Vue3 was announced officially on September 18th, 2020.

While it introduces a variety of features/improvements, I would like to focus on the new Composition-API syntax for creating components and the reactivity.

If you are curious as to why Options API was replaced with a new syntax, the RFC for Composition-API is a good place to get an in-depth look to the thought process/reasoning of the core team and the Vue community.

To be able to explain Component-API in a readable fashion, I have decided to break it down into a few parts:

  1. Component Syntax.
  2. Reactivity.
  3. Composables.

Composition-API: Component Syntax

As we reviewed in the Vue2 section above, up until now we had the Options-API (Official) and the Class Component (Unofficial) as approaches for creating a component.

Composition-API introduced a new syntax that aims to reduce the boilerplate code necessary for writing a new component plus adding Typescript support.

To start creating the component we will be using defineComponent .
Instead of using export default, we will be using export default defineComponent({}), thus getting the added benefit of typings support for each of the properties/methods within the method.

Within defineComponent, you will now notice we have a new method called setup that concentrates our parameters and methods (removing the need for the data and methods section from Vue2).

To expose our defined parameters and methods to the View, setup expects us to return them as part of the return parameters of the method.

Worth mentioning that while the data and the methods parts are gone from Composition-API, props are still defined the same way. Additionally computed and watch can now be called from setup directly.

Composition-API: Reactivity

For those who are coming from React, the way Composition-API handles reactivity may feel a bit similar to useState (while not the same).

There are 2 ways to make a variable reactive (2-way, or in plain English, the ability to reflect a change on both the view and in the code).

Reactive: Method that takes an object as a parameter and converts it to become reactive (Behind the scenes, Vue will iterate recursively and convert each variable in the object to a reactive variable).

Using the new Vue3 reactive method

Both in a template and the code, accessing data from a reactive variable is like any other JavaScript variable.

Accessing variables from a reactive object in a template and in code

While it is straightforward to access a reactive object, the one thing to be careful about is deconstructing an object.
During a deconstruction of an object, Vue loses track of the reactivity of the object. To maintain reactivity we will need to use a method called toRefs to convert the variables inside the object back to becoming reactive.

Deconstructing a reactive object, what to do or do not do

Ref: Method that takes a primitives value (string, number, boolean, etc.) and convert it to become reactive (Behind the scenes, Ref will converts (boxing) the value to an object and passes it to reactive method).

For those who come from an object-oriented background, the name ref refers to reference and can be thought of as a change from a value type to a reference type.

Using the new Vue3 ref method

Ref value can be accessed directly when passed to the template, however unlike reactive, to access the variable from the code we will need to add .value to it or alternatively, if we want to access it the same way as when using reactive, we will need to use a method called unref.

Accessing a ref variable in a template and code

While I did not cover here everything related to Reactivity for Vue3, I do hope that this brief introduction is helpful to better understand what changed.

For more information on reactivity in Vue3, I would recommend videos such as Reactivity made easy, Fundamentals of Reactivity in Vue3, and Reactivity in Vue 3 — How does it work?.

Composition-API: Composables

The last part of our dive to Composition-API will discuss the concept of composables.

One of the considerations behind creating the Composition-API was code sharing. How to define logical pieces of code that could be shared easily between components.

For those familiar with Vue2 and wondering why not just use Mixins, you are welcome to read this article that goes more in-depth to the topic.

As we have seen in the Vue2 section, a popular approach for code sharing is Plugins. However. in Vue3 the setup method is called before the component is created, thus preventing the usage of this keyword to access global properties.

Instead, with the new Composition-API we can use reactive , ref and even computed even outside of a component to build a reusable function (for those who come from React, this is similar to the Hooks approach).

Defining a composable for saying Hello World

Since a composable is just a function, we can import it and use it in our component.

Using a composable in a component

Vue2 the Vue3 Way: Composition-API

Now that we learned what new features the Vue3 Composition-API is bringing, we will take a look at how can we still maintain our created Vue2 application, but with the same syntax as Vue3.

Fortunately for us, the Vue core team worked hard to back-port the Composition-API functionality as a plugin.

To add Composition-API to the project, run the following command:
yarn add @vue/composition-api .

Once the command is finished, open the main.ts file (src/main.ts) and add the following code to it.

Setup for using the Composition-API plugin in Vue2

Now we can convert our previous code example to use the new Composition-API syntax and maintain combability when migrating in the future to Vue3.

A simple example of how to update a message and display it using features from Composition-API

Summary

This article came out much longer than I anticipated (I am still considering whether to break it down into separate articles), but hopefully, it has helped you to take your first steps in the Vue world with setting up your first project, learning some of the concepts that Vue2 has, understanding what the Vue3 Composition-API has to offer and even getting to change your code to use it in Vue2.

In the next part of the series, we will take our existing code and convert it to a closer real-world example (Login form) using Composition-API and state management with Pinia.

For any questions, concerns, suggestions, welcome to leave a comment and I will be happy to answer.

--

--