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

You're reading from  Front-End Development Projects with Vue.js

Product type Book
Published in Nov 2020
Publisher Packt
ISBN-13 9781838984823
Pages 774 pages
Edition 1st Edition
Languages
Authors (5):
Raymond Camden Raymond Camden
Profile icon Raymond Camden
Hugo Di Francesco Hugo Di Francesco
Profile icon Hugo Di Francesco
Clifford Gurney Clifford Gurney
Profile icon Clifford Gurney
Philip Kirkbride Philip Kirkbride
Profile icon Philip Kirkbride
Maya Shavin Maya Shavin
Profile icon Maya Shavin
View More author details

Table of Contents (16) Chapters

Preface
1. Starting Your First Vue Project 2. Working with Data 3. Vue CLI 4. Nesting Components (Modularity) 5. Global Component Composition 6. Routing 7. Animations and Transitions 8. The State of Vue.js State Management 9. Working with Vuex – State, Getters, Actions, and Mutations 10. Working with Vuex – Fetching Remote Data 11. Working with Vuex – Organizing Larger Stores 12. Unit Testing 13. End-to-End Testing 14. Deploying Your Code to the Web Appendix

5. Global Component Composition

Overview

In this chapter, you will learn how to reduce duplication in your Vue.js application code using global abstractions, new composition models, and new types of components. You will experiment with Vue.js mixins, plugins, and new types of components and ways of composing them.

By the end of this chapter, you will be able to identify situations where mixins and plugins can be used to achieve global composition and keep code DRY (don't repeat yourself) in a Vue.js application, as well as how to define global components, functional components, and components in non-Vue files. You will also be able to contrast the advantages and drawbacks of global composition and select the right abstraction to maximize component flexibility.

Introduction

Component nesting is an approach to composition where the application is built up from smaller units (components). The application can be thought of as components fitting within each other. In this scenario, any shared functionality will be provided through components. Vue.js provides other methods of composition.

Component-based composition can be very verbose and will mean we repeat imports wherever a certain piece of functionality is needed. This does not follow the DRY principle. To avoid this duplication and verbosity, we can globally register mixins, plugins, and components to inject the globally available resources to be used throughout the application. This can reduce friction and frustration at having to type out import MyComponent from ... in every consumer of MyComponent.

Much in the same way, applications can be built from different types of primitives (mixins, plugins, and components). For maximum flexibility, components can be defined in different ways...

Mixins

Mixins can add methods, properties, and default life cycle methods to components that consume them. In the following example, we are defining a mixin that adds a greet method and a greeting field to the component's data function:

export default {
  methods: {
    greet(name) {
      return `${this.greeting} ${name}`
    }
  },
  data() {
    return {
      greeting: 'Hello'
    }
  }
}

Mixins allow multiple components' shared functionality to be defined independently. They are used through a mixins component property, which accepts an array.

In the App.vue file, we can consume the mixin by setting the component's mixins property.

The properties and methods of the mixin are then available in the component (just as they would be if they were defined in the component...

Plugins

Vue.js plugins are a way to add custom functionality to Vue.js globally. Good candidates for plugins are core to the application and used widely. 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 directive, mixin, component, and filter definitions.

Plugins can inject functionality by registering directives and filters. They can also add global and instance Vue.js methods, as well as defining global component mixins.

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

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

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

const plugin = {
  install...

Globally Registering Components

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

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...

Maximizing Component Flexibility

Vue.js components take props and slots as input; their output is rendered as HTML and emitted events.

To maximize component flexibility, it always makes sense to leverage slots and props.

Leveraging props and default values judiciously means a component can be reused and extended. For example, instead of hardcoding a value in the component, we could set it as a default prop. In this case, date defaults to the current date, new Date(). We then extract the epoch using a computed property:

<template>
  <div>Date as epoch: {{ epoch }}</div>
</template>
<script>
export default {
  props: {
    date: {
      type: Date,
      default() {
        return new Date()
      }
    }
  },
  computed: {
   ...

Using Vue.js Components without a .vue Single-File Component

Most of the examples we have seen of Vue.js components have leveraged .vue single-file components.

This is not the only way to define a Vue.js component. In this section, we will look at four different ways to define Vue.js components without using a .vue file.

Evaluating these options will help us understand what a Vue.js component is at its core.

Runtime Definition with a String Template

A component can use a template property that accepts a string value. This is commonly called a string template. This template is evaluated at runtime (in the browser).

We can define a component in the StringTemplate.js file by defining an object with a template property:

export default {
  template: `<div>String Template Component</div>`
}

This can then be consumed from the App.vue file, as follows:

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

The Vue component Tag

JSX and render functions are great for situations where the component being rendered needs to be very dynamic.

The way to achieve this within regular Vue.js templates is by using the component tag.

The component tag uses the is prop to dynamically select which component will be rendered.

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...

Functional Components

Functional components are a subset of regular Vue.js components. They do not have state or a component instance. They can be thought of as render functions (as shown earlier in this chapter) to which props are passed.

Note

We can mark components as functional, which means that they are stateless (no reactive data) and instance-less (no this context).

See the Vue.js documentation for more (https://vuejs.org/v2/guide/render-function.html#Functional-Components).

Functional components can only access props, children, slots, and scoped slots, as passed from their parent component. They also receive references to parents and listeners.

The following is a Greet component (in the Greet.vue file). Note the functional annotation in template:

<template functional>
  <div>Functional Component: {{ props.greeting }} {{     props.audience }}</div>
</template>

Functional components must access props through props.propName...

Summary

Throughout this chapter, we have looked at global composition patterns and advanced component setups that can be used to reduce duplication throughout a Vue.js application.

First, we learned about mixins, which explicitly share functionality while letting components have the last say and saw the exceptions to this rule. We then saw how plugins are a great hook into multiple Vue.js primitives.

Next, we looked at how prescriptive patterns maximize component reusability in Vue.js. Ideas such as leveraging props to delegate data, slots to delegate templates, and implementing interfaces that allow components to be used with Vue-idiomatic shorthand such as v-model were shown.

We also took an in-depth look at what Vue.js components are beyond .vue files. We delved into what a Vue.js component is by introducing string templates, render functions, and JSX, as well as the requirements for each of these approaches to work. The component tag and keep-alive showed another...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Front-End Development Projects with Vue.js
Published in: Nov 2020 Publisher: Packt ISBN-13: 9781838984823
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 $15.99/month. Cancel anytime}