Getting Started with VueJS: Introduction to Vue 3
Tags: vue, cli, webdev, javascript
Published: 2022-10-14 18:24:04

[Vue 3](https://vuejs.org/guide/introduction.html) is a JavaScript framework for building user interfaces. It builds on top of standard HTML, CSS and JavaScript, and provides a declarative and component-based programming model that helps you efficiently develop user interfaces that can be either simple or complex.

At the end of this article, you should be familiar with Vue 3 features and its breaking changes. You’ll also understand how to transition from Vue 2 to Vue 3, know how to install plugins and dependencies using Command Line and Graphic User interfaces, and, lastly, be familiar with the Vue 3 V-model and its issues.

## Features of Vue 3

Vue 3 is faster, smaller in file size, and has better TypeScript support than other frameworks. Other features of Vue 3 are:

- [Composition API](https://vuejs.org/api/) (now built-in): Composition API is a built-in feature of Vue 3 and is currently available to Vue 2 through the officially maintained[ @vue/composition-api](https://github.com/vuejs/composition-api) plugin. In Vue 3, it's mainly used together with the[ <script setup>](https://vuejs.org/api/sfc-script-setup.html) syntax in single-report additives. Here is a basic instance of a issue using Composition API:


```
<script setup>
import { ref, onMounted } from 'vue'

// reactive state
const count = ref(0)

// functions that mutate state and trigger updates
function increment() {
  count.value++
}

// lifecycle hooks
onMounted(() => {
 console.log(`The initial count is ${count.value}.`)
})
</script>

<template>
 <button @click="increment">Count is: {{ count }}</button>
</template>
```

[Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) is pre-installed in Vue 3 and is ready to use right out of the box without any further configuration.

Using the Composition API has two primary benefits:

- Improved organization
- Code sharing and reuse


If you think you don't need the composition API, you can always utilize the conventional methods used in Vue 2 as Vue 3 will still support Options API.

### Suspense

This feature renders a default or backup component while waiting for the main component to fetch the data. Async operations are sometimes used to fetch data from the server.[ Suspense](https://vuejs.org/guide/built-ins/suspense.html) handles this for us rather than handing the template with v-if and then sending it back when we provide the data. When you want to build an API callback to display the content once it has fully loaded or display a loading notice while it’s processing, suspense can be useful.

```
<Suspense>
 <Admin />
 <template #fallback>
   Loading...
 </template>
</Suspense>
```

### Multiple V-models

You may be aware that two-way binding is done using the v-model. It’s primarily utilized with form elements. Even custom components are used with it, occasionally. One v-model might be used per component under Vue 2. You can bind as many v-models as you want to your custom components in Vue 3.

## Breaking Changes of Vue 3

There are too many ground-breaking improvements introduced by Vue 3 for one article to properly address. Go to the official[ documentation](https://v3-migration.vuejs.org/breaking-changes/) for further information.

### **Fragments**

[Fragments](https://v3-migration.vuejs.org/new/fragments.html), multi-root node components supported by Vue 3, are now available. Older versions of Vue did not support this.

```
<!-- Layout.vue -->
<template>
 <header>...</header>
 <main v-bind="$attrs">...</main>
 <footer>...</footer>
</template>
```

### Teleport

A feature of Vue 3 called[ Teleport](https://vuejs.org/guide/built-ins/teleport.html) lets you choose where to render an HTML document with numerous DOM parents. Now, HTML may be rendered in several DOM locations without the need for additional components or a global state.

```
<!-- In some nested Vue component -->
<NestedComponent>
 <Teleport to="#teleport-target">
 <PopUp />
 </Teleport>
</NestedComponent>
<!-- before closing body tag in index.html -->
<div id="teleport-target"></div>
```

### Mounting

When we[ mount](https://vuejs.org/guide/essentials/application.html#mounting-the-app) an application in Vue 3, the element's innerHTML is replaced by the rendered content of the application:

```
const app = Vue.createApp({
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  template: `
    <div id="rendered">{{ message }}</div>
  `
})

app.mount('#app')
```

When this app is added to a page with a div with the id="app" , the following will happen:

```
<body>
  <div id="app" data-v-app="">
    <div id="rendered">Hello Vue!</div>
  </div>
</body>
```

### Filter

[Vue.js](https://v2.vuejs.org/v2/guide/filters.html) allows you to define filters that can be used to apply common text formatting. Filters are usable in two places: **mustache interpolations and v-bind expressions**. Filters should be appended to the end of the JavaScript expression, denoted by the “pipe” symbol.

However, filters are depreciated in[ Vue 3](https://v3-migration.vuejs.org/breaking-changes/filters.html)! The same functionality can be implemented in a simple plugin, but expressions with filters are invalid since the filter's pipe interferes with the Javascript bitwise operator. Because of this, the suggested alternative is to use a method.

Let’s look at how filters work in Vue 2 and how they can be implemented in Vue 3.

In **Vue 2,** we define local filters in a component’s options:

```
filters: {
      currencyUSD(value) {
 return '$' + value
      }
    }
  }
</script>
```

Now, this is how it can be implemented in **Vue 3:** Instead of filters, you replace them with method calls or computed properties as seen below:

```
computed: {
      accountInUSD() {
 return '$' + this.accountBalance
      }
    }
  }
</script>
```

## **How to** Migrate **from Vue 2**

The additional plugins and frameworks you use and how well they support Vue 3 will determine how difficult it is to migrate an old Vue 2 project to Vue 3.

To make the process easier, Vue offers a migration build that enables you to convert gradually while maintaining some backwards compatibility.

They also offer simple [ step-by-step](https://v3-migration.vuejs.org/) migration instructions.

### Migration Steps

The manual lists the processes to complete migration, which includes:

- Upgrade Vue and include the compatibility package.
- Fix the warnings that the compatibility package has revealed.
- Update your app's mounting.
- Update any Vue plugins you're using, including vuex and vue-router.
- After addressing all alerts, remove the compatibility package.


Overall, the migration is simple to complete, and many official plugins (such as vue-router, vuex, and others) offer helpful migration instructions.

## Getting Started with Vue 3

Before you start, you’ll need:

- [Node.js 16.15.1 LTS](https://nodejs.org/en/) and above installed.
- Code editor: Visual Studio Code is strongly advised.
- Vue’s latest version running on your computer.
- [Vue CLI 3.0](https://cli.vuejs.org/guide/installation.html) installed, or you can update the previous CLI version with the following command line:


```
npm update -g vue-cli
```

To install a fresh, new CLI:

```
npm install -g @vue/cli
```

### Quick Set Up

_Note:  For quick set up of your_[ Vue 3 Project](https://vuejs.org/guide/quick-start.html) _that doesn’t require the Vue CLI:_  You can use Vue 3 with or without a build phase (whose configuration is based on[ Vite](https://vitejs.dev/), a contemporary, lightweight, and incredibly quick frontend build tool), depending on your use case and preferences.

## Starting a New Project

There are two main methods for launching a new Vue project aside from the step described above:

- The command line interface technique.
- The graphical user interface technique.


### Command Line Interface Technique

You can still start new projects using the[ Command Line Interface](https://cli.vuejs.org/guide/creating-a-project.html), but the syntax has changed. To do so, simply type the following command in your terminal:

```
vue create vue-app
```

Here, the application you wish to create is called Vue-app. The prompts that follow this command will all be in the terminal.

After executing the command, you will be presented with three pre-set options:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image9_836740d94181c0e6bcbf2474f492444e.png" alt="The three options to create a Vue app."/></figure>

You can select the Vue version, which is the second and third that come with Babel and ESLint. They will be packaged exclusively. This example has already been preset, but you can choose the "manually select features" configuration if you wish to incorporate other helpful dependencies like the Vue Router, Vuex and so forth.

By hitting Space, you may go through the list of available dependencies and pick the ones you want to enable:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image4_0aecc9c4e181af7d00ab3f6bc3ef738c.png" alt="The list of available dependencies."/></figure>

It will then ask you numerous configuration-related questions, starting with the Vue version:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image10_269e8040b9baffb4578ee3264a905207.png" alt="Choosing a Vue version."/></figure>

For each module you chose that can be customized, questions are listed after:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image11_a31d7ab5a075b7a4b637b2d91299876c.png" alt="The questions associated with the chosen model."/></figure>

The CLI will then ask you whether you wish to store these choices as a preset. If you do, you can choose from this preset in addition to the two default ones the next time you create a new application:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image3_b43f94b58618b4c0d1716dfdf2f50048.png" alt="The option to save as a preset."/></figure>

Once the creation process is completed, you can run the app in the development server directly from the CLI by using the following command:

```
cd vue-app
npm run serve
```

Then, your browser will open up localhost:8080, where you’ll see that the app is running:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image1_83af5af094ea8c3673f64dfbdd32d3f1.png" alt="The Vue welcome screen."/></figure>

### Graphic User Interface Technique

The[ GUI](https://cli.vuejs.org/guide/creating-a-project.html) tool, a web interface option of the terminal for users who would prefer a graphical interface over a command line interface, is one of the features that the Vue CLI 3.0 comes with. With the help of this tool, you can build projects, add plugins and install dependencies. You can also perform operations like serving up or creating the production version of the application.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image5_4e128af4e645e169f9696d78dc907541.png" alt="The GUI tool."/></figure>

The graphical user interface technique entails using the GUI tool to quickly and easily establish a new project.

Run the GUI command shown below by opening the terminal on your computer:

```
vue ui
```

Your browser will instantly launch the GUI interface at[ http://localhost:8000/project/select](http://localhost:8000/project/select). At first, it appears like this:

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image8_9ef5a97494fc3ef8d6057fa92a0813ff.png" alt="The Vue project manager screen."/></figure>

A file manager will open in the same interface when you click the “create” button to start a new project. You can find earlier Vue projects with a Vue symbol on them while browsing through your project files. Click the “create new project here” option on the website, then select the folder where you want your new application to be built. This will guide you through two simple registration steps.

- Details: Here, we’ll select the project name. Choose a package manager that uses either yarn or npm. You can also toggle the option to overwrite if the contents of the folder already exist. Finally, you can decide whether to create a Git repository for your project. It has the option to select the selected initial commit message.
- Presets: Presets are plugin and configuration associations. Once you've selected a feature, you can optionally save them as presets so you can reuse them in future projects without having to reconfigure everything. There are three categories of presets. The default presets include only Babel and ESLint plugins and the basic Vue configuration. Custom presets allow you to choose your own plugins, and remote presets allow you to choose presets from a remote Git repository.


After a few seconds, you’ll be notified that a new project has been created, and the project dashboard will open in your application's UI.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image6_aff23a5e1a0ff63d26ed68a62172f0d8.png" alt="The new Vue project dashboard."/></figure>

### Installing Plugins/Dependencies

The new CLI is plugin-based by design.[ Plugins](https://vuejs.org/guide/reusability/plugins.html) are now used by the new CLI to change the configurations of our project setup at any time. Plugins are now recognized as features in Vue and even as features from third parties. They are essentially dependencies with additional abilities to modify the Webpack configuration.

The primary Vue core dependencies and the development dependencies make up Vue's dependencies. These can be set up using either the GUI or the CLI method.

#### Installing Plugins with GUI and CLI

GUI:

The second icon in the sidebar of the project dashboard is for plugins. The plugins you installed during the registration process at the beginning of this article—ESLing, Babel, and the CLI service (the service on which the plugins run) —will appear when you click on it.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image2_28a290f4d8f13a0f2bb1b60789517854.png" alt="The available project plugins."/></figure>

It's simple to add a new plugin; simply click the “add plugin” button, and a list of plugins will appear. You can also use the search field to enter a search word, and the service will return a list of plugins that are currently accessible. When you select a plugin, such as Vuetify, an install button will appear; clicking it will add the plugin to your project and automatically alter its Webpack configuration.

_**Note**__:_ [ The current version of Vuetify](https://vuetifyjs.com/en/) _is not compatible with Vue 3, and according to_[ the Vuetify Docs](https://vuetifyjs.com/en/introduction/roadmap/#in-development)_, Vuetify intends to release a more harmonious version for Vue 3 in the near future (It’s best to wait for it). On that note, there’s a_[ Vuetify 3 beta](https://next.vuetifyjs.com/en/getting-started/installation/) _version for testing purposes (not production), which will be used to illustrate how to install the Vuetify plugin with CLI._

CLI:

To install the Vuetify plugin via the CLI, browse to the project directory and issue the add command as follows:

```
vue add vuetify
```

Once prompted, choose Vuetify 3 Preview:

```
? Choose a preset:
  Configure (advanced)
  Default (recommended)
  Vite Preview (Vuetify 3 + Vite)
  Prototype (rapid development)
❯ Vuetify 3 Preview (Vuetify 3)
```

This alters all of the files that the Vuetify plugin will touch after being installed into your Vue applications. Some plugins have additional prompts that guide you through installing them.

#### Installing Dependencies with GUI and CLI

GUI:

The third symbol in the sidebar of the project dashboard represents dependencies. The Vue and core requirements are in the main part. The dev dependencies include the template compiler, ESLint dev dependencies, and many other things.

<figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/image7_05c6b01fc858e78a8b6162c84d5c1271.png" alt="The available project dependencies."/></figure>

To enable the use of bootstrap classes in your project, you must first install the bootstrap dependency. To do this, click the “Install Dependency” button, then type "bootstrap" into the search bar, and then click “Install.” After a brief delay, you’ll be informed of the new installation.

CLI:

You must enter the project directory and execute the “install” command as follows to install the bootstrap dependency directly using the CLI:

```
npm install bootstrap
```

### Creating a Single Vue Component

Create a new file called helloworld.vue in a folder of your choice. Copy the following code into the file and then save it:

```
// helloword.vue file
<template>
 <div class="hello">
 <h1>{{ msg }}</h1>
 <h3>Installed CLI Plugins</h3>
 <h3>Essential Links</h3>
 <h3>Ecosystem</h3>
 </div>
</template>
<script>
 export default {
    name: 'HelloWorld',
    props: {
      msg: String
    }
  }
</script>
```

With this command, you can run it on the dev server:

```
vue serve helloWorld.vue
```

This launches a Vue single component on your localhost in the same way that a whole project would.

## Vue 3 V-Model

To give developers additional control and flexibility when creating custom components that allow two-way data binding, the v-model directive has been updated in Vue 3.

Custom inputs that work with[ v-model](https://v3-migration.vuejs.org/breaking-changes/v-model.html) can also be made using custom events.

Keep in mind that

```
<input v-model="name" />
```

has the same effect as

```
<input
  :value="name"
  @input="name = $event.target.value"
/>
```

On a component, the v-model instead accomplishes the following:

```
<CustomInput
 :modelValue="name"
 @update:modelValue="newValue => name = newValue"
/>
```

However, for this to function properly, the input inside the component must:

- Bind the `modelValue` prop to the value attribute.
- Emit an `update:modelValue` on input with the fresh value.


This is how it works:

```
<!-- CustomInput.vue -->
<script>
export default {
  props: ['modelValue'],
  emits: ['update:modelValue']
}
</script>

<template>
 <input
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
  />
</template>
```

Now, this component should operate flawlessly with the v-model:

```
<CustomInput v-model="name" />
```

The[ Component Events](https://vuejs.org/guide/components/events.html#usage-with-v-model) section contains more information about unique v-model modifiers.

## Problems with Vue 3

Although we made every effort to have the migration build behave as closely as possible to Vue 2, there are some[ restrictions](https://v3-migration.vuejs.org/migration-build.html#known-limitations) that can preclude your app from being eligible for upgrading:

- **Support for Internet Explorer 11:** Vue 3 has formally abandoned its plan to support IE11. You must continue using Vue 2 if you still need to support Internet Explorer 11.
- **Server-side rendering:** Although a bespoke SSR system can be migrated, it is considerably more difficult to do so. The migration build can be utilized for SSR. In general, `@vue/server-renderer` should be used in place of `vue-server-renderer`. Vite should be used with Vue 3 SSR instead of the bundle renderer that Vue 3 used to offer. Waiting for Nuxt 3 is generally preferable if you are using Nuxt.js.
- **Dependencies that rely on undocumented or internal APIs of Vue 2**: The use of private attributes on VNodes is the most typical scenario. It is advisable to wait for the Vue 3 compatible versions of component libraries like[ Vuetify](https://vuetifyjs.com/en/),[ Quasar](https://quasar.dev/) or[ ElementUI](https://element.eleme.io/#/en-US) if your project depends on them.


## When to Use

- If you need better TypeScript support, Vue 3 is far better than the previous version!
- If performance problems persist despite optimizations. Vue 3 performs better than Vue 2 since Vue 3 was created from scratch.
- If your dependencies allow it, use Vue 3.


## Conclusion

The framework in Vue 3 was completely redesigned. It has some ground-breaking features for creating large-scale corporate software, along with improved TypeScript support, better tree-shaking, lower size and increased speed.

In the migration process, it had previously been easy to switch from node-sass, which has been depreciated to sass, as we mentioned. Since sass-loader v10 requires Webpack 5, which is a migration for another day, we were unable to get past that version.

The default v-model property in Vue 3 now goes by the name `modelValue` instead of its previous name of `value`, and the default v-model event now goes by the name `update:modelValue` instead of its previous name of `input`.