Getting Started with VueJS: Introduction to Vue 3

vue 3 complete guide
Spread the love

Introduction

Vue 3 is like a helpful tool for making websites. It uses the usual stuff we use for websites – HTML, CSS and JavaScript. But makes it easier to build things. It works by letting you describe what you want and helps you organize your code into little building blocks.

By the end of this read you’ll know what Vue 3 can do and what changed from Vue 2. You’ll also get the hang of moving your code from Vue 2 to Vue 3. You’ll even learn how to add extra features (plugins) and pieces your website needs (dependencies) using both the nerdy command line and the friendlier point-and-click way.

NOTE : The current latest stable version of Vue is v3.4.5.

Features Of Vue3

Vue 3 comes with some cool features that make it stand out. It’s faster meaning your websites load quickly. It’s also smaller in file size. Which is like saying it won’t take up much space. Plus if you’re Familier with TypeScript then its more interesting.

Composition API in Vue

One big thing in Vue 3 is the Composition API. It’s like a set of tools that makes your code look cleaner and helps you organize things better. In the past you had to add an extra piece to Vue 2 to use it. But now it’s already there in Vue 3. Look at this simple example:

<template>
  <div>
    <h1>Vue.js Ref and mounted Demo</h1>
    <p>Current count: {{ count }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0,
    };
  },
  mounted() {
    // Accessing the ref value after the component is mounted
    console.log("Component has been mounted. Initial count:", this.count);
  },
  methods: {
    incrementCount() {
      // Modifying the ref value
      this.count += 1;
    },
  },
};
</script>

It might look a bit sophisticated. But it makes your code cleaner and helps you share and reuse your code better. And don’t worry If you’re used to the old way in Vue 2 you can keep using it in Vue 3 too.

Suspense in Vue3

Vue 3 introduced the Suspense feature to make it easier to manage asynchronous operations and handle loading states in components. Suspense enables you to declaratively specify loading indicators or fallback content while waiting for asynchronous data to be resolved.

<template>
  <Suspense>
    <!-- Async component to be loaded -->
    <AsyncComponent />
    <!-- Fallback content or loading indicator -->
    <template #fallback>
      <p>Loading...</p>
    </template>
  </Suspense>
</template>

<script>
// AsyncComponent.vue
const AsyncComponent = () => import('./AsyncComponent.vue');

export default {
  name: 'ParentComponent',
  components: {
    AsyncComponent,
  },
};
</script>
  • The Suspense component wraps the asynchronous component (AsyncComponent in this case).
  • The fallback template provides content that is displayed while the asynchronous component is being loaded.
  • When the asynchronous component is resolved and loaded it replaces the fallback content.

This helps to create a smoother user experience. Especially when dealing with components that fetch data asynchronously. Vue3 Suspense simplifies the handling of loading states and improves the overall readability of code.

Multiple V-models

In VueJS v-model is a way to connect data between your code and what users see. In Vue2 you could use it with one thing at a time. But in Vue3. It’s like having more than one remote control for different parts of your app. You can connect and control multiple things easily. Making it simpler to manage how your app responds to user input.

Fragments in Vue3

In Vue3 fragments allow you to have multiple root nodes in a component. Which is a feature that wasn’t directly supported in older versions of Vue. A fragment is essentially a way to group multiple HTML elements without needing to wrap them in a single parent element.

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

Teleport in Vue3

In Vue3 the teleport feature allows you to render a component’s children at a different place in the DOM outside of its parent hierarchy. This can be useful for scenarios like modals or tooltips where you want the component’s content to be rendered in a different part of the DOM but controlled by the original component.

<template>
  <div>
    <button @click="toggleModal">Open Modal</button>

    <!-- Using teleport to render modal content outside the current parent hierarchy -->
    <teleport to="body">
      <div v-if="showModal" class="modal">
        <button @click="closeModal">Close Modal</button>
        <p>Modal Content Goes Here</p>
      </div>
    </teleport>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showModal: false,
    };
  },
  methods: {
    toggleModal() {
      this.showModal = !this.showModal;
    },
    closeModal() {
      this.showModal = false;
    },
  },
};
</script>

<style>
/* Some basic styling for the modal */
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  border: 1px solid #ccc;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style>
  • The teleport component is used to render the modal content (<div class="modal">) outside of its current parent hierarchy specified by the to=”body” attribute.
  • The modal is conditionally displayed based on the showModal data property.
  • Clicking the “Open Modal” button toggles the visibility of the modal and the modal content is teleported to the body element.

This allows you to create components with content that is visually part of one component but rendered in a different part of the DOM for better control and positioning.

Mounting in Vue3

In Vue3 when you mount an application the process involves replacing the inner HTML of a specified element with the rendered content of the Vue application. This behavior is part of the initialization process where Vue takes control of the specified DOM element and manages its content.

  1. Specified Element : You identify a specific HTML element in your HTML file where you want your Vue application to be mounted. This is typically done using the el option when creating a Vue instance.
  2. Mounting Process : When you call the mount method Vue takes over the specified element and replaces its inner HTML with the rendered content of your Vue component or application.
  3. Rendering Content : Vue renders the content of your component or application and injects it into the specified element. This content is what you define in your Vue component’s template and it could include dynamic data, directives and other Vue features.

Filters in Vue3

In Vue.js filters were a convenient way to apply common text formatting to data in Vue 2. They could be used in mustache interpolations and v-bind expressions by appending them to the end of the JavaScript expression using the “pipe” symbol (|). However in Vue3 filters have been deprecated due to interference with the JavaScript bitwise operator. Instead the recommended alternative is to use methods or computed properties to achieve the same functionality.

Here’s a breakdown of how filters were used in Vue 2 and how the equivalent functionality can be implemented in Vue 3

Filters in Vue2

<template>
  <div>
    <p>{{ amount | currencyUSD }}</p>
  </div>
</template>

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

In Vue2 you could define local filters within a component’s options. The currencyUSD filter takes a value and adds a ‘$’ symbol to it.

Using Methods or Computed Properties :

<template>
  <div>
    <p>{{ accountInUSD }}</p>
  </div>
</template>

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

In Vue3 filters have been deprecated and instead you can achieve the same result by using methods or computed properties. Here the accountInUSD computed property performs the same task as the Vue 2 filter appending a ‘$’ symbol to the accountBalance data property.

This transition allows for more consistency in Vue3 code and avoids the interference issues with the JavaScript bitwise operator that were present in Vue 2 filters.

Problems With Vue3

While Vue 3 aims to provide a smooth migration process from Vue 2 there are certain limitations and considerations that might affect your upgrade

  • No More Internet Explorer 11 Support : Vue3 has decided to drop support for Internet Explorer 11. If your app still needs to cater to IE11 users you’ll need to stick with Vue2.
  • Server-side Rendering (SSR) Challenges : While you can migrate a custom SSR system it’s trickier than in Vue2. The migration build supports SSR but it’s recommended to use @vue/server-renderer instead of the old vue-server-renderer. For Vue3 SSR with Vite it’s suggested to use Vite instead of the bundle renderer. If you’re a Nuxt.js user waiting for Nuxt 3 might be a more comfortable option.
  • Dependencies Tied to Vue 2 Internals : Some dependencies especially component libraries like Vuetify, Quasar or ElementUI might rely on undocumented or internal APIs of Vue2. It’s smart to hold off on upgrading until these libraries release versions compatible with Vue3.

In simpler terms upgrading to Vue 3 might not be the best fit if your app still needs to support Internet Explorer 11 involves complex server-side rendering or relies on external dependencies not yet compatible with Vue3. It’s like upgrading a system make sure all the parts are ready for the switch.

Conclusion

In Vue3 the framework underwent a complete redesign. Introducing groundbreaking features that enhance the development of large-scale corporate software. Notable improvements include enhanced TypeScript support more efficient tree-shaking, reduced package size and overall increased performance.

During the migration process a notable change was transitioning from the deprecated node-sass to sass. However upgrading to sass-loader v10 posed a challenge as it requires Webpack 5—a migration that was deferred for future consideration.

In terms of syntax adjustments Vue3 renamed the default v-model property from ‘value’ to ‘modelValue’. Similarly the default v-model event was changed from ‘input’ to ‘update:modelValue’. These modifications reflect the evolution of Vue.js introducing more clarity and alignment in its syntax and functionality.

FAQs

What are the key features of Vue3 ?

Vue3 introduces several notable features including improved performance, smaller file size, enhanced TypeScript support and the Composition API. The Composition API provides tools for cleaner code organization and better maintainability.

How does Vue3 handle asynchronous operations with the Suspense feature ?

Vue3 introduces the Suspense feature to manage asynchronous operations more effectively. It allows you to declaratively specify loading indicators or fallback content while waiting for asynchronous data to be resolved and improving the user experience.

Can I still use multiple v-models in Vue3 ?

Yes, in Vue3 you can use multiple v-models. Allowing you to connect and control different aspects of your application with ease. This provides a more flexible way to manage user input and state.

What are the considerations for upgrading to Vue3 ?

Considerations for upgrading to Vue 3 include the dropped support for Internet Explorer 11. Potential challenges with server-side rendering and the need to wait for compatible versions of dependencies that rely on Vue 2 internals. Ensure that your application is ready for these changes before upgrading.


Spread the love

Similar Posts

One Comment

Comments are closed.