Reader small image

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

Product typeBook
Published inMar 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803234991
Edition2nd Edition
Languages
Tools
Right arrow
Authors (4):
Maya Shavin
Maya Shavin
author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

Raymond Camden
Raymond Camden
author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

View More author details
Right arrow

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 2023Publisher: PacktISBN-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.
undefined
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

Authors (4)

author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco