Solomon Eseme I am a software developer who is geared toward building high-performing and innovative products following best practices and industry standards. I also love writing about it at masteringbackend.com. Follow me on Twitter @kaperskyguru, on Facebook, onLinkedIn, and on About.Me at Solomon Eseme." Follow me: Twitter, Facebook, LinkedIn, about.me

What’s new in Vue 3

4 min read 1285

New Features in Vue 3 and How to Use Them

The long-awaited Vue 3 was officially released on 18 September 2020.

There is updated documentation for this new version, which Vue published alongside its migration guide. Both are highly readable, well-structured resources to help you get started using Vue 3.

Working with Vue 3 is as easy as using the previous version. If you discover any bugs or issues along the way, you can report them using Vue Issue Helper.

In this guide, we’ll walk you through the current state of the Vue framework and give you some tips and foundational knowledge to help you start using Vue 3.

We’ll cover the following:

  1. Vue 3 Performance
  2. Tree-shaking support
  3. The Composition API
  4. Teleport
  5. Fragments
  6. Improved TypeScript support
  7. Other breaking changes
  8. Experimental features
  9. Migrating from Vue 2
  10. Getting started with Vue 3

Let’s get started!

Vue 3 Performance

Among the highlights of Vue 3 is its performance. Overall, Vue 3 is about 55 percent faster, updates are up to 133 percent faster, and memory usage is down to 54 percent. This is achieved by completely rewriting the DOM implementation using TypeScript.

Other performance improvements include:

  1. More efficient component initialization
  2. SSR is 2–3x faster
  3. Compiler-informed fast paths
  4. Update performance is 1.3–2x faster

Tree-shaking support

Tree-shaking is the process of eliminating dead, useless, or unused code, thereby decreasing the build size of an app.

With the new changes, Vue 3’s build size is 13.5kb. It slims down nicely to 11.75kb when you strip away everything but the Composition API support.

Even with all the bells and whistles, Vue 3 is only 22.5kb, which is still lighter than Vue 2 with all features included due to tree-shaking.

The Composition API

This is one of the biggest changes to Vue. It is entirely additive and introduces breaking changes to the previous Options API. While the Composition API advances, the Options API will continue to be supported.

// src/components/UserRepositories.vue

export default {
  components: { RepositoriesFilters, RepositoriesSortBy, RepositoriesList },
  props: {
    user: { type: String }
  },
  setup(props) {
    console.log(props) // { user: '' }

    return {} // anything returned here will be available for the rest of the component
  }
  // the "rest" of the component
}

Teleport

Teleport is a new Vue 3 feature that allows you to decide where to render a piece of HTML with many DOM parents. You can now render HTML in different places in the DOM without creating a global state or different components.

app.component('modal-button', {
  template: `
    <button @click="modalOpen = true">
        Open full screen modal! (With teleport!)
    </button>

    <teleport to="body">
      <div v-if="modalOpen" class="modal">
        <div>
          I'm a teleported modal! 
          (My parent is "body")
          <button @click="modalOpen = false">
            Close
          </button>
        </div>
      </div>
    </teleport>
  `,
  data() {
    return { 
      modalOpen: false
    }
  }
})

When the button is clicked, Vue renders the content of the modal inside the body tag as a child of the body tag.

Fragments

Vue 3 now supports mulitroot node components called fragments. This was not supported in older versions of Vue.



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

Improved TypeScript support

Vue 3’s codebase is written in TypeScript. This enables it to automatically generate, test, and bundle up-to-date type definitions.

Vue now supports JSX and class components are still supported with TypeScript. In other words, you can create a Vue app with either TypeScript or JavaScript, depending on your expertise.

interface Book {
  title: string
  author: string
  year: number
}

const Component = defineComponent({
  data() {
    return {
      book: {
        title: 'Vue 3 Guide',
        author: 'Vue Team',
        year: 2020
      } as Book
    }
  }
})

Other breaking changes

Vue 3 introduces too many breaking changes to adequately cover in one article. For more on the following, head to the official docs.

  • Global and internal APIs now support tree-shaking
  • Render function API changed
  • The Global Vue API now uses an application instance
  • Functional components are only created with plain functions
  • The function attribute on single-file component (SFC) is deprecated
  • The model component option and v-bind‘s sync modifier are removed in favor of v-model arguments
  • The defineAsyncComponent method is required to create async components
  • It’s best practice to always declare the component data option as a function
  • The $scopedSlots property is replaced with $slots
  • New attributes coercion strategy

Experimental Features

Vue 3 comes with many great features and enhancement to the Options API and also introduces some experimental features. You can use these features in your development phase and send feedback to the Vue core team.

Suspense

Suspense is an essential feature even though it’s still in the experimental phase. It serves as a component that renders fallback contents when a condition is met and is used to conditionally render contents.

suspense comes in handy when you want to make an API call back to display the content when fully loaded or show a loading message while it’s processing.

<Suspense>
  <template >
    <Suspended-component />
  </template>
  <template #fallback>
    Loading...
  </template>
</Suspense>

The above is a simple example of how you can use suspense and fallback to handle API requests.

<script setup>

When using the <script> tag in Vue 3 to create a single-page component with the new Composition API, you’d put all your methods and variables inside the setup() method. But with the new <script setup>, you can simply create your component without using the setup() method or returning anything.


More great articles from LogRocket:


The old way:

<script>
import { ref } from 'vue'
export default {
  setup() {
    const variable = ref(0)
    const inc = () => variable.value++
    return {
      variable,
      inc,
    }
  },
}
</script>

The new way:

<script setup>
  import { ref } from 'vue'

  export const count = ref(0)
  export const inc = () =&gt; count.value++
</script>

Without using the setup method, everything still works and the code is more concise.

<setup vars>

This is also a very useful feature introduced in Vue 3, it allows developers to reference component state inside our style declaration. A very basic example will be declaring a reactive property and accessing it inside the <style> tag.

<template>
  <div class="text-color">This is my text </div>
<template>

<script>
  export default {
    data() {
      return {
          color: 'green'
      }
    }
  }
</script>

<style vars="{ color }">
  .text-color {
    color: var(--color);
  }
</style>

By using the vars and var properties, you can declare a CSS property with a reactive value.

Migrating from Vue 2

If you have a project written in Vue 2, you might be wondering how migrations will be handled. The Vue team will release one last update for Vue 2 that is backward-compatible with Vue 3. The team will also add depreciation warnings for changes that will cause your app to break. This long-term support (LTS) version will last for 18 months, which means it will still get security updates and is absolutely safe to keep using.

The migration guide, which is still in beta, will include a compatibility build for Vue 3 and also a command-line migration tool, which will help with automatic migration and provide hints where necessary.

Getting started with Vue 3

npm init vite-app hello-vue3


const HelloVueApp = {
  data() {
    return {
      message: 'Hello Vue!!'
    }
  }
}

Vue.createApp(HelloVueApp).mount('#hello-vue')
//--------------------------------------------------

&lt;div id="hello-vue" class="demo"&gt;
  {{ message }}
&lt;/div&gt;

Conclusion

In this tutorial, we explored the new features and breaking changes introduced with Vue 3. We also demonstrated how to start a new Vue 3 project using the vite library and how to migrate your old Vue 2 project to Vue 3.

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - .

Solomon Eseme I am a software developer who is geared toward building high-performing and innovative products following best practices and industry standards. I also love writing about it at masteringbackend.com. Follow me on Twitter @kaperskyguru, on Facebook, onLinkedIn, and on About.Me at Solomon Eseme." Follow me: Twitter, Facebook, LinkedIn, about.me

Leave a Reply