Introduction

Are you working on VueJs 2?
Is there a requirement to migrate from Vue 2 to Vue 3?
Are you frustrated and stuck with the entire migration process?
Do you want to end your struggle?

We are here to help you! Many of our technical readers have suggested writing a descriptive tutorial for beginners on migration from VueJS 2 to VueJS 3. So, here we are, back with the step-by-step guideline. Don’t worry if you are not familiar with the migration process. We will be learning it from scratch.

So, let’s understand why migration from Vue 2 to Vue 3 is essential.

Why Should You Migrate from Vue 2 to Vue 3?

The IT industry evolves with time so does the technology, and so do its technical requirements. To keep the project updated is inevitable even if one of the technology from the tech stack has been updated. The reason behind this is whenever the technology evolves, it updates its dependencies and libraries, it removes unwanted garbage code, it also adds new features that enhance the development and workflow.

Vue 3 is comparatively new updated technology. There’s no need to immediately update your entire Vue 2 project to Vue 3, but you should start planning it out. Because as time will pass, lesser third-party libraries will be supporting version 2 and maybe VueJS will not lesser the development support for version 2.

VueJs 3 is written from scratch and comes with even better performance, better tree-shaking, smaller size, improved TypeScript support, and many new features for developing large-scale enterprise software.

You don’t need to worry about it. Here in this tutorial, we will learn how to migrate from Vue 2 to Vue 3.

Tutorial Goal: Vue 2 to Vue 3 Migration

The migration process can be quite complicated and hectic. So, to ease out the process we have used a basic demo application that fetches the users’ data from JSON Placeholder API and will build a simple UI to display it.

So, here’s what we will be covering in our tutorial.

  • Overview of Vue 3
  • Building VueJS 2 Demo App
  • Update CDN scripts
  • Update VueJS instance
  • Update VueJS Router instance

Overview of Vue 3

Vue 3 was officially launched on 18th September 2020 and is considered to be the default version from 7th February 2022.

Vue 3 Features

  • Composition API
  • SFC Composition API Syntax Sugar (< script setup >)
  • Fragments
  • Teleport
  • Emits Component Option
  • SFC State-driven CSS Variables

Migrate from Vue 2 to Vue 3: Breaking Changes

Following are the breaking changes that you should look into for migration.

  • Global API
  • Template Directives
  • Working of the Components
  • Render Function
  • Custom Elements
  • Other Minor Changes (that might affect your project)
  • Removed APIs

Let’s get started with the migration process.

Create VueJs 2 Project

Here we used Vue-2 to create our app.

Vue-2 to create Vuejs app

Navigate to your project and run the application using these commands.

Copy Text
cd vue2-to-vue3-example
npm run serve 

Your browser will show the default UI as shown below.

VueJs app UI

Vue2 package.json file.

Vue2 package.json file

Build User Interface

Each Vue Component lives inside the .vue file. A Vue component consists of three parts.

1. < template > – Contains component’s HTML
2. < script > – All the JavaScript logic is written inside this tags
3. < style >> – Component’s CSS is written inside this tags

Are you looking for proficient VueJs developers for your project?
Bacancy is here for you! Contact us now and hire Vue developer to build, optimise, and deploy your application.

Creating Components

Here we create two components:

  • Home Component
  • UserList Component

App.vue

App.vue is the parent of all components. It defines the template of our page.

Copy Text
<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view/>
  </div>
</template>

Home.vue

In Home.vue component we have done the following things:

  • We have called mapState, mapGetters, and mapActions from vuex
  • We use a ‘mounted’ hook to fetchUsers
  • We have passed ‘getAllUsers’ (mapGetter) and isLoading(mapState) as props to ‘UserList’ component.
Copy Text
<template>
  <div class="home">
    <h1 class="text-3xl mb-6 font-bold">Users List</h1>
    <user-list :getAllUsers="getAllUsers" :isLoading="isLoading"></user-list>
  </div>
</template>


UserList.vue

Here we will receive ‘getAllUsers’ and ‘isLoading’ props. Once the data is fetched we will use a table to display users’ data. v-for will loop over the getAllUsers array on ‘tbody’ element and display user data. We will also implement one of the features offered by Vue2, i.e., ‘filters.’ Here we will use the ‘SetEmail’ filter. It will return the user’s email with 1st letter small.

Copy Text
<template>
  <div class="container">
    <div v-if="isLoading">
        <h1 class="text-3xl font-bold">Loading...</h1>
    </div>
    <div class="overflow-x-auto relative" v-else>
      <table class="w-5/6 ml-auto mr-auto text-sm text-left text-gray-500 dark:text-gray-400">
        <thead
          class="text-xs text-gray-700 uppercase bg-gray-300 dark:bg-gray-700 dark:text-gray-400"
        >
          <tr>
            <th scope="col" class="py-3 px-6">Name</th>
            <th scope="col" class="py-3 px-6">Username</th>
            <th scope="col" class="py-3 px-6">Email</th>
            <th scope="col" class="py-3 px-6">Company Name</th>
          </tr>
        </thead>
        <tbody v-for="user in getAllUsers" :key="user.id">
          <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-100">
            <td class="py-4 px-6">{{user.name}}</td>
            <td class="py-4 px-6">{{user.username}}</td>
            <td class="py-4 px-6">{{user.email | setEmail}}</td>
            <td class="py-4 px-6">{{user.company.name}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>


Configuring Store: index.vue

Copy Text
import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: [],
    isLoading: false
  },
  mutations: {
    GET_USERS(state, users) {
      state.users = users
    }
  },

  actions: {
    async fetchUsers({commit, state}){
      state.isLoading = true;
      const res = await axios.get('https://jsonplaceholder.typicode.com/users')
      commit("GET_USERS", res.data)
      state.isLoading = false
    }
  },
  
  getters: {
    getAllUsers(state){
      return state.users
    }
  },
  modules: {
  }
}

Output

Output

How to Migrate from Vue 2 to Vue 3?

Now, we are done building a basic demo application with VueJS 2. Before, moving on to the files here is the basic process that’s need to be followed to migrate from Vue2 to Vue3:

  • First, we make sure that our @vue/cli-service is in the newest version.
  • To update our vue-cli command is – vue upgrade
  • Now modify our ‘package.json’ file. Here we have to uninstall vue2 and vue-template-compiler. They are not needed for VueJS.
  • Run the npm install command to install vue3, @vue/compat, and compiler @vue/compiler-sfc.

Install [email protected] and [email protected] and update them to the latest version as shown below.

Create a vue.config.js file to set up the compiler option to get migration build work.

Create a vue.config.js file

Once done with the basic configuration, start the development server. You will be notifies with some error messages. So, let’s get started to solve them

main.js

First, we will fix the main.js file for vue3. Below is the comparison.

// main.js

fix the main.js file for vue3

Router File: index.js

Now, open router file and use the below code for migration.

open router file

Store File: index.js

Now update store file.

The remaing code in the store file would be as it is.

package.json file

We also need to update the package.json file. Use the below image where we have updated the dependencies.

update the package.json file

Home.vue

Vue 3 came with a new feature called ‘compositionApi’, which is a replacement for ‘optionsApi’ However, you can also use optionsApi.

Here we use compositionApi.

  • ‘onMounted’ is called after the component has been mounted. To use it we have to import it from ‘vue.’
  • ‘setup()’ hook serves as the entry point for Composition Api usage in components.
  • ‘computed()’ is same as computed() property in optionsApi. To use it in compositionApi, we have to import it from ‘vue.’ It takes a getter function and returns a read-only reactive ‘ref’ object for the returned value from the getter.
  • To access the store within the ‘setup’ hook, we can call the ‘useStore()’ function. It is equivalent to retrieving ‘this.$store’ within a component using ‘Options API.’
Copy Text
<template>
  <div class="home">
    <h1 class="text-3xl mb-6 font-bold">Users List</h1>
    <user-list :getAllUsers="getAllUsers" :isLoading="isLoading"></user-    list>
  </div>
</template>


UserList.vue

In Vue 3, ‘filters’ has been removed. Instead of filters, we can use the ‘computed()’ property.

Copy Text
<template>
  <div class="container">
    <div v-if="isLoading">
        <h1 class="text-3xl font-bold">Loading...</h1>
    </div>
    <div class="overflow-x-auto relative" v-else>
      <table class="w-5/6 ml-auto mr-auto text-sm text-left text-gray-500 dark:text-gray-400">
        <thead
          class="text-xs text-gray-700 uppercase bg-gray-300 dark:bg-gray-700 dark:text-gray-400"
        >
          <tr>
            <th scope="col" class="py-3 px-6">Name</th>
            <th scope="col" class="py-3 px-6">Username</th>
            <th scope="col" class="py-3 px-6">Email</th>
            <th scope="col" class="py-3 px-6">Company Name</th>
          </tr>
        </thead>
        <tbody v-for="user in getAllUsers" :key="user.id">
          <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-100">
            <td class="py-4 px-6">{{user.name}}</td>
            <td class="py-4 px-6">{{user.username}}</td>
            <!-- <td class="py-4 px-6">{{user.email | setEmail}}</td> -->
            <td class="py-4 px-6">{{user.email.toString().charAt(0).toLowerCase() + user.email.toString().slice(1)}}</td>
            <td class="py-4 px-6">{{user.company.name}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>


Github Repository: vue2-to-vue3-example

So, these were the steps to implement the migration process from vue 2 to vue 3. You can visit the source code: vue2-to-vue3-example. Clone the repository and experiment with the code.

Conclusion

I hope the tutorial will get you started with how to migrate from Vue 2 to Vue 3. When it comes to migrating an enterprise-level or large-scale project it will definitely demand a lot of time, management, and effort. But, you can always split the module and plan accordingly. If you are a VueJS enthusiast and want to learn more about VueJS, then the VueJS tutorials page is for you.

Need Assistance with Migration?

Connect with us to migrate your code to latest version of Vue.js to hassle out bugs and incompatibilities.

Migrate Today

Get In Touch

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.