Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Frontend Development Projects with Vue.js 3 - Second Edition

You're reading from  Frontend Development Projects with Vue.js 3 - Second Edition

Product type Book
Published in Mar 2023
Publisher Packt
ISBN-13 9781803234991
Pages 628 pages
Edition 2nd Edition
Languages
Authors (4):
Maya Shavin Maya Shavin
Profile icon Maya Shavin
Raymond Camden Raymond Camden
Profile icon Raymond Camden
Clifford Gurney Clifford Gurney
Profile icon Clifford Gurney
Hugo Di Francesco Hugo Di Francesco
Profile icon Hugo Di Francesco
View More author details

Table of Contents (20) Chapters

Preface 1. Part 1: Introduction and Crash Course
2. Chapter 1: Starting Your First Vue Project 3. Chapter 2: Working with Data 4. Chapter 3: Vite and Vue Devtools 5. Part 2: Building Your First Vue App
6. Chapter 4: Nesting Components (Modularity) 7. Chapter 5: The Composition API 8. Chapter 6: Global Component Composition 9. Chapter 7: Routing 10. Chapter 8: Animations and Transitions 11. Part 3: Global State Management
12. Chapter 9: The State of Vue State Management 13. Chapter 10: State Management with Pinia 14. Part 4: Testing and Application Deployment
15. Chapter 11: Unit Testing 16. Chapter 12: End-to-End Testing 17. Chapter 13: Deploying Your Code to the Web 18. Index 19. Other Books You May Enjoy

Global Component Composition

In the previous chapter, we learned how to use Composition API to create component logic and how to write custom reusable composables in a Vue application. There are many approaches to sharing similar logic between other components besides composables. In this chapter, we will learn how to use mixins, plugins, and how to render dynamic components.

By the end of this chapter, you will be ready to organize your code using mixins and plugins, achieve global composition, and keep code DRY (Don’t Repeat Yourself) in any project. You will also understand the advantages and drawbacks of global composition, thus deciding the right approach to maximize a component’s flexibility.

This chapter covers the following topics:

  • Understanding mixins
  • Understanding plugins
  • Registering components globally
  • Understanding component tags
  • Writing functional components

Technical requirements

In this chapter, you need to set up a basic Vue project following the instructions in Chapter 1, Starting Your First Vue Project. It’s recommended to create a single-file Vue component to practice the examples and concepts mentioned easily.

You can find this chapter’s source code here: https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter06.

Understanding mixins

With mixins, we can add additional methods, data properties, and life cycle methods to a component’s option object.

In the following example, we first define a mixin that contains a greet method and a greeting data field:

/** greeter.js */
export default {
  methods: {
    greet(name) {
        return `${this.greeting}, ${name}!`;
    }
  },
  data() {
    return {
      greeting: 'Hello'
    }
  }
}

Then we can use the greeter mixin by importing and assigning it as part of the mixins field in the component’s option object, as follows:

<script>
import greeter from './mixins/greeter.js'
export default {
  mixins: [greeter]
}
</script>

mixins is an array that accepts any mixin as its element, while a mixin...

Understanding plugins

Vue plugins are a way to add custom functionality to Vue.js globally. Classic examples of plugin candidates are translation/internationalization libraries (such as i18n-next) and HTTP clients (such as the axios, fetch, and GraphQL clients). The plugin initializer has access to the Vue instance, so it can be a good way to wrap global directives and components and inject resources across the application.

A Vue plugin is an object that exposes an install method. The install function is called with an app instance and options:

const plugin = {
  install(app, options) {}
}

Within the install method, we can register directives and components and add global and instance properties and methods:

const plugin = {
  install(app, options) {
    app.directive('fade', { bind() {} })
    app.component(/*Register component globally*/)
    app.provide(/*Provide a resource to be...

Globally registering components

A reason for using plugins is to reduce boilerplate in all Vue application files by removing imports and replacing it with access to this.

Vue.js components are usually defined in a single-file component and imported explicitly. Much for the same reasons as we define global methods and properties, we might want to register components globally. This will allow us to use these components in all our other component templates without having to import them and register them under the components property.

A situation where this can be very useful is when using a design system or when a component is used across the code base.

Globally registering a component helps with some types of updates, such as if the filename is not exposed to the consumer so that when changing the filename, there is only one path to update as opposed to one per user.

Let’s assume we have a CustomButton component in the CustomButton.vue file that looks as follows:

...

Understanding components

JSX and render functions are great for situations where the component being rendered needs to be very dynamic. We can also achieve this capability using the Vue component.

To render a dynamic component, we use a component tag with a bound is property (here, we are using the shorthand :is, which is equivalent to v-bind:is):

<component :is="componentName" />

We will now learn how to render dynamic components using a name or component reference.

Rendering dynamic components by name or component reference

Let’s say we have a grid that contains items whose display can be toggled between a card display (a design element with an image and text) or an image-only view.

First, we need to import the relevant components and register them as components. We will also set some fixture data to loop through for the grid:

<template>
  <div id="app">
    <div class="grid"...

Writing functional components

In Vue 2.0, you can declare a component as a functional one by setting the functional field to true in the component’s options:

export default {
  functional: true,
}

This can also be done by setting functional directly on the template tag:

<template functional>
  <!— template code -->
</template>

And you can set how to render the component using the render() method of the component or the template section. However, if both fields exist, Vue takes the render() method.

In Vue 3.0 onward, however, Vue removed the functional attribute and you can only declare a functional component using a JavaScript function, which is the render function Vue will trigger to create the component:

const functionComp = (props, context) => {
 return h(/*…*/)
}

Once declared as functional, the component does not have any reactive state, and you can’t access this instance since it is not...

Summary

Throughout this chapter, we have looked at global composition patterns and advanced component setups that we can take advantage of to create a reusable code base for a Vue.js application. We learned about mixins, plugins, how to use component tags for dynamic component rendering, and functional components, both stateful and stateless.

So far, we have learned how to build applications in terms of components, mixins, and plugins. To build applications that span multiple pages, we need to implement routing. This is what we will tackle in the next chapter.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Frontend Development Projects with Vue.js 3 - Second Edition
Published in: Mar 2023 Publisher: Packt ISBN-13: 9781803234991
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}