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

Nesting Components (Modularity)

In the previous chapter, we learned how to initialize, build, and debug a simple Vue application. In this chapter, you will discover how to modularize a Vue application using component hierarchies and nesting. This chapter introduces concepts such as props, events, prop validation, and slots. It also covers how to use refs to access DOM elements during runtime.

By the end of this chapter, you will be able to define communication interfaces between components using props, events, and validators, and be ready to build components for your Vue component library or a Vue application.

This chapter covers the following topics:

  • Passing props
  • Understanding prop types and validation
  • Understanding slots, named slots, and scoped slots
  • Understanding Vue refs
  • Using events for child-parent communication

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 Vue component in a single file to practice the examples and concepts covered here with ease.

The complete code for this chapter is available on GitHub at: https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter04.

Passing props

Props in the context of Vue are fields defined in a child component 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 accepts props

Let’s look at a simple HelloWorld single-file component. You can find this at ./src/components/HelloWorld.vue, generated automatically when you create a Vue project with Vite.

Note how the msg value is set in the props array and that it is interpolated as a value using {{ msg }}.

The props property of a Vue component can be an array of strings or an object literal, each property field of which is a component’s prop definition.

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

<template>
  <div class="hello">
 ...

Understanding prop types and validation

We use props to define the interfaces of Vue components and ensure other developers use our components correctly. We need to define their interfaces with types and validation. Vue offers that capability out of the box by changing how we pass the props as string elements to the props property in an object form.

Primitive prop validation

Assume we want a Repeat.vue component that takes a times prop and a content prop and then calculates the array of repetitions using computed based on the times value. 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...

Understanding slots, named slots, and scoped slots

Slots are sections of a component where the template/rendering is delegated back to the parent of the component. We can consider slots as templates or markup that are passed from a parent to a child for rendering in its main template.

Passing markup to a component for rendering

The simplest type of slot is the default child slot.

We can define a Box component with a slot as follows:

<template>
  <div>
    <slot>Slot's placeholder</slot>
  </div>
</template>

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

<template>
  <div>
    <Box>
      <h3>This whole h3 is rendered in the slot</h3>
    </Box>
  </div>
</template>
<script>
import Box from './components/Box.vue'
export...

Understanding Vue refs

In Vue, refs are references to DOM elements or other component instances that have been mounted to the DOM.

One of the major use cases for refs is direct DOM manipulation and integration with DOM-based libraries (that usually take a DOM node they should mount to), such as an animation library.

We define refs by using the syntax ref="name" on a native element or child component in the template. In the following example, we will add a reference to the input element under the name theInput:

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

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

Now let’s programmatically focus on the input field when clicking...

Using 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 offers custom events.

In a component, we can emit an event using the $emit method; with this.$emit('eventName', payload) within <script>; or just with $emit within the template section.

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: {
    send() {
      ...

Summary

Throughout this chapter, we have explored how to enable data communication between components using props and custom events. We explored slots and saw how we enable UI template customization for a component from its parent. We also learned how to use refs to unlock integration opportunities with third-party JavaScript or DOM libraries by allowing us to access DOM elements directly.

We’re now able to create and compose components that clearly define their interfaces with inputs (props and slots) and outputs (rendered templates and events), while also visiting commonly faced use cases (such as wrapping a DOM library).

In the next chapter, we’ll look at advanced component composition patterns and techniques that enable better code reuse.

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