Reader small image

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

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838984823
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
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

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

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

Philip Kirkbride
Philip Kirkbride
author image
Philip Kirkbride

Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.
Read more about Philip Kirkbride

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

View More author details
Right arrow

4. Nesting Components (Modularity)

Overview

In this chapter, you will discover how to modularize a Vue.js application using component hierarchies and nesting. This chapter introduces concepts such as props, events, prop validation, and slots. You will learn how to contrast them and identify which concept should be applied based on the situation. You will then practice implementing a component that encapsulates direct DOM manipulation using refs. You will also learn how to identify component composition scenarios where slots, named slots, and scoped slots can be used. You will then identify when to abstract functionality into filters.

By the end of this chapter, you will be able to define communication interfaces between components using props, events, and validators. You will be exposed to refs to wrap JavaScript libraries as Vue.js components and identify the pitfalls of the Vue.js context when using components.

Introduction

In the previous chapter, we learned how to initialize, build, and debug a simple Vue.js application. In this chapter, we will have a closer look at how to leverage component composition to enable code re-usability.

Reusable and extensible components are core to building products around a component library. A component library allows a team to build a project with high velocity and high consistency.

If a component library in Vue.js does not expose the right extension points, what often happens is that the component from the library is copied over into the application's code base. This leads to duplicated code and reduced cohesion from a design point of view.

In Chapter 3, Vue CLI, we learned how to create simple components in Vue. Components are Vue instances that can be instantiated and rendered multiple times. Since there can only be one root component, most components in an application are rendered by another component. For parent components to communicate...

Passing Props

Props in the context of Vue.js are fields, defined in a child component, that are accessible on that component's instance (this) and in the component's template.

The value of a prop depends on what the parent passes in its template to the child component at render time.

Defining a Simple Component That Takes Props

Let's look at a simple Hello single-file component. This can be found in a ./src/components/Hello.vue file (in a Vue CLI-generated project). Note how the who value is set in the props array and that it is interpolated as a value using {{ who }}. The props property of a Vue.js component can be an array of strings or an object literal.

When a value is defined in props, it is then accessible as an instance variable in the template section of the Vue.js component:

<template>
  <div>
    <h1>Hello {{ who }}</h1>
  </div>
</template>
<script>
export...

Prop Typing and Validation

Props define the interface of Vue.js components. As JavaScript is a dynamically typed language, Vue.js provides a tool we can use to validate the shape and types of props.

To validate prop types, the props component property in its object literal form should be used (as opposed to the simpler array form).

Primitive Prop Validation

Say we want a Repeat.vue component that takes a times prop, as well as a content prop. We can define the following:

<template>
  <div>
    <span v-for="r in repetitions" :key="r">
      {{ content }}
    </span>
  </div>
</template>
<script>
export default {
  props: ['times', 'content'],
  computed: {
    repetitions() {
      return Array.from({ length: this.times });
 &...

Slots, Named Slots, and Scoped Slots

Another component composition pattern that enables reusability in Vue.js is slots.

Slots are sections of a component where the template/rendering is delegated back to the consumer of the component.

Here, props can be thought of as data that is passed from a parent to a child for said child to run some logic or to render it.

Slots can be thought of as templates or markup that's passed from a parent to a child for said child to render.

Passing Markup to Be Rendered in a Child Component

The simplest type of slot is the default child slot.

We can define a Box component with a slot as follows. Note that this Box component does very little:

<template>
  <div>
    <slot />
  </div>
</template>

The following markup is for the parent component (src/App.vue):

<template>
  <div>
    <Box>
   ...

Template Logic Sharing with Filters

To share template logic, Vue.js has filters.

Filters can be used in mustache interpolations ({{ interpolatingSomething }}) or in expressions (for example, when binding a value). filter is a function that takes a value and outputs something that can be rendered (usually a String or a Number).

So, an example filter called truncate would be used in a template as follows (here, we have put some long placeholder text):

<template>
  <div id="app">
    {{ message | truncate }}
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Lorem ipsum dolor sit amet, consectetur adipiscing         elit, sed do eiusmod tempor incididunt ut labore et dolore         magna aliqua. Ut enim ad minim veniam, quis nostrud         exercitation llamco laboris nisi ut aliquip ex ea commodo...

Vue.js refs

In Vue.js, refs are references to DOM elements or other components. This occurs programmatically.

A large use case for refs is direct DOM manipulation and integration with DOM-based libraries (that usually take a DOM node they should mount to).

Refs are defined using ref="name" on a native element or child component in the template. In the following instance, the input will be stored in a theInput ref:

<template>
  <div id="app">
    <input ref="theInput" />
  </div>
</template>

Refs can be accessed from the Vue.js component instance through this.$refs[name]. So, in the previous example, where we had a ref defined as ref="theInput", we can access it through this.$refs.theInput.

To focus the input when a button is clicked, we could write the following:

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

Vue.js Events for Child-Parent Communication

We have already seen that props are used to pass data from a parent component to a child component.

To pass data from a child component back to a parent component, Vue.js has custom events.

In a component, an event can be emitted using the $emit instance method. It can be used from within the script section using this.$emit('eventName', /* payload */), but it is also exposed within the template section as $emit.

Assuming we have got a reactive instance property, this.message, we could emit a send event with the message value in the script section using this.$emit. This could be the basis for a MessageEditor component:

<script> 
export default {
  data () {
        return {
            message: null
        }
    },
  methods: {...

Summary

Throughout this chapter, we have looked at Vue.js primitives that allow us to build components in such a way that they can be composed efficiently.

Props and slots are used to defer behavior within a component to whichever parent component is rendering them. Props, with their ability to be validated, are great for passing data into nested components. Slots are geared toward yielding control of rendering back to the parent component. Events enable child components to send data back to their parent, thus completing the parent-child communication cycle (props down, events up).

Global templating helpers can be encapsulated in filters to reduce boilerplate and increase code reuse. Refs unlock integration opportunities with third-party JavaScript or DOM libraries by allowing us to access DOM elements directly.

We're now able to compose and create components that clearly define their interfaces with inputs (props and slots) and outputs (rendered templates and events...

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 2020Publisher: PacktISBN-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.
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 $15.99/month. Cancel anytime

Authors (5)

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

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
Philip Kirkbride

Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.
Read more about Philip Kirkbride

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