Vue.js 3 Design Patterns and Best Practices - Pablo David Garaguso - E-Book

Vue.js 3 Design Patterns and Best Practices E-Book

Pablo David Garaguso

0,0
28,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

If you’re familiar with the progressive Vue framework for creating responsive user interfaces, you’ll be impressed with its latest iteration, Vue 3, which introduces new concepts and approaches design patterns that are uncommon in other libraries or frameworks. By building on your foundational knowledge of Vue 3 and software engineering principles, this book will enable you to evaluate the trade-offs of different approaches to building robust applications.
This book covers Vue 3 from the basics, including components and directives, and progressively moves on to more advanced topics such as routing, state management, web workers, and offline storage. Starting with a simple page, you’ll gradually build a fully functional multithreaded, offline, and installable progressive web application.
By the time you finish reading this Vue book, not only will you have learned how to build applications, but you’ll also understand how to solve common problems efficiently by applying existing design patterns. With this knowledge, you’ll avoid reinventing the wheel for every project, saving time and creating software that’s adaptable to future changes.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 429

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Vue.js 3 Design Patterns and Best Practices

Develop scalable and robust applications with Vite, Pinia,and Vue Router

Pablo David Garaguso

BIRMINGHAM—MUMBAI

Vue.js 3 Design Patterns and Best Practices

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Jane D’Souza

Senior Content Development Editor: Feza Shaikh

Technical Editor: Saurabh Kadave

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Ponraj Dhandapani

Marketing Coordinators: Anamika Singh, Namita Velgekar, and Nivedita Pandey

First published: May 2023

Production reference: 1240423

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN: 978-1-80323-807-4

www.packtpub.com

To Elizabeth, Adele, Gabriel, and Eleonora, my wonderful children, whose love and affection kept me going every day. I truly believe the world is a better place because of them.

– Pablo David Garaguso

Foreword

Does the following situation sound familiar to you?

You are invited by a friend to a dinner party. A delicious meal is served, and everyone enjoys the evening. Something about the meal – the combination of flavors – tastes extra special. You want to recreate the meal for yourself to impress your own family and friends. You almost don’t dare to ask, but when you do, your host tells you happily about their “secret” method. However, they are an experienced chef and what is simple for them sounds complex to you. Since you feel unsure where to start, your host assures you they will write down and explain all the steps so you can learn how to recreate the meal. By the end of the evening, you have the information you need to produce something special on your own.

By now, you might know where this is going. You chose this book because you are interested in web development. Looking at the field as a whole may feel overwhelming, and you need a clear explanation of the smaller components so you know where to start. Combining the right ingredients (here, libraries and frameworks) with the guidance of an experienced “chef” will enable you to set off on your own journey.

Luckily, you have found a guide written by a master in his field. In my time with Pablo Garaguso, I’ve found him to have the “magic sauce” that allows him to come to impressive solutions quickly. He applies his knowledge and creativity to inspire his team members. Moreover, he is a wonderful teacher and willing to share freely. He gives you the background information you need to understand how and why to do things a certain way. By following his advice, you will gain a deeper understanding of web development and not only be able to apply the principles in this book but also start to experiment with them and create your own solutions for future projects.

Pablo provides information on setting up a project, constructing UI components, creating single-page apps and progressive web apps, data flow, multithreading, common UI and UX patterns, testing, source control, and deploying your application. He even includes helpful hints on migrating from Vue 2 to Vue 3.

I hope you will enjoy working through the examples provided as much as I did.

I invite you to join in on this journey of discovery!

Olaf Zander Development Manager, FamilySearch

Contributors

About the author

Pablo David Garaguso was born in Argentina, and since he was a child, he had a special interest in computers. He programmed his first game at the age of 12 years old, and since then, his interest only kept growing. As an adult, he graduated in computer sciences from CAECE University, Mar del Plata, with a specialty in human-computer interfaces. Later in life, he went back to school to work on his MBA at CEMA University, Buenos Aires, with a specialization in corporate entrepreneurship and management. He worked in South America and Europe for almost 20 years in multiple positions. He discovered Vue early on, but it was not until version 2 that he adopted it for his projects. He currently works as a solutions architect and full-stack engineer in Finland, where he resides with his children. His software solutions are used all around the world in specific areas. In his limited spare time, being a natural storyteller, he is also an author of interactive fiction and novels.

About the reviewers

Fotis Adamakis is an experienced software engineer with a strong background in JavaScript, testing, and accessibility. He is proficient in writing clean, maintainable code for large-scale applications, following best practices and industry standards. Fotis has a particular passion for Vue and has developed a high level of expertise in using it.

Aside from his technical skills, Fotis is also a skilled author and speaker on frontend development topics. He has been invited to speak at various conferences, where he shares his knowledge and insights on the latest trends in the field.

He continually seeks new challenges and opportunities to grow and expand his skills.

Simon Nørlund Eldevig is an experienced frontend engineer who has worked in frontend development for over 7 years. His extensive experience has made him an expert in building scalable and responsive web applications.

Throughout his career, Simon has worked with a variety of clients, ranging from small to large enterprises, helping them to develop elegant and user-friendly interfaces. He takes great pride in staying up to date with the latest trends and technologies in frontend development, which has allowed him to create cutting-edge solutions.

Simon is a true frontend enthusiast, which is why he’s also an organizer of Vue.js meetups in his local community.

Tamrat Assefa is a full-stack developer from Addis Ababa, Ethiopia. He has a bachelor’s degree in software engineering from Addis Ababa University. After landing small projects for local clients while still in school, Tamrat quickly jumped into the web development scene. He has been developing web applications for more than 7 years now and has a very deep knowledge of Vue.js, his favorite JavaScript frontend library. When he is not building features and squashing bugs, you can find him working on cars or playing his favorite game, Dota 2.

Table of Contents

Preface

1

The Vue 3 Framework

The progressive framework

Using Vue in your web application

The bundler way, a better way...

Understanding single-file components

Different strokes – options, composition, and script setup API

Exploring built-in directives in Vue 3

v-bind: (shorthand ":")

v-show

v-if, v-else, and v-else-if

v-for and :key

v-model

v-on: (and the shorthand @)

Built-in components

Book code conventions

Variables and props

Constants

Classes and component names

Functions, methods, events, and filenames

Instances

Summary

Review questions

2

Software Design Principles and Patterns

What are the principles of software design?

A non-exclusive list of design principles

Separation of concerns

Composition over inheritance

Single responsibility principle

Encapsulation

KIC – keep it clean

DRY – don’t repeat yourself

KISS – keep it simple and short

Code for the next

What is a software design pattern?

A quick reference list of patterns

The singleton pattern

The dependency injection pattern

The factory pattern

The observer pattern

The command pattern

The proxy pattern

The decorator pattern

The façade pattern

The callback pattern

The promise pattern

Summary

Review questions

3

Setting Up a Working Project

Technical requirements

Project setup and tools

Folder structure and modifications

Integration with CSS frameworks

The w3.css framework

FontAwesome is just awesome

Vite configuration options

The To-Do app

Summary

Review questions

4

User Interface Composition with Components

Technical requirements

Page composition with components

Step 1 – identify layouts and user interface elements

Step 2 – identify relationships, the data flow, interactions, and events

Step 3 – identify user interactivity elements (inputs, dialogs, notifications, and more)

Step 4 – identify design patterns and trade-offs

Components in depth

Local and global components

Static, asynchronous, and dynamic imports

Props, events, and the v-model directive

Custom input controllers

Dependency injection with Provide and Inject

Special components

Slots, slots, and more slots...

Composables and mixins

Dynamic components with “component:is”

A real-world example – a modals plugin

Setting up our development project

The design

The implementation

Implementing our new To-Do application

A small critique of our new To-Do application

Summary

Review questions

5

Single-Page Applications

Technical requirements

What is a SPA?

The Vue 3 router

Installation

A new To-Do application

Routes’ definition and the Router object

Router template components

Nested routes, named views, and programmatic navigation

Exploring authentication patterns

Simple username and password authentication

OpenID and third-party authentication

Passwordless or one-time password (OTP) authentication

2FA - Two Factors Authentication

Web3 authentication

Summary

Review questions

6

Progressive Web Applications

Technical requirements

PWAs or installable SPAs

Upscaling a SPA into a PWA

The manifest file

Testing your manifest

Install prompt

Service workers

Vite-PWA plugin

Testing your PWA score with Google Lighthouse

Summary

Review questions

7

Data Flow Management

Technical requirements

Components’ basic communication

Implementing an event bus with the Singleton and Observer patterns

Implementing a basic reactive state

Implementing a powerful reactive store with Pinia

Browser data stores – session, local, and IndexedDB

Experimenting with reactivity and Proxies patterns

Summary

Review questions

8

Multithreading with Web Workers

Technical requirements

An introduction to web workers

Implementing a Web Worker

The business delegate pattern

The dispatcher pattern

Establishing a communication pipeline with the web worker

Accessing IndexedDB with DexieJS in the web worker

Consuming a RESTful API with the web worker

A simple NodeJS server for testing

Summary

Review questions

9

Testing and Source Control

Technical requirements

What are testing and TDD

What to test

Our base example application

Installation and use of Vitest

Special assertion case – fail on purpose

Special assertion case – asynchronous code

Installation of Vue Test Utils

In-source testing

Coverage

The Vitest UI

What is source control... and why?

Source control with Git

Installation on Windows systems

Installation on Linux systems

Installation on macOS systems

Using Git

Managing branches and merges

Merging conflicts

Working with remote repositories

Continuous Integration and Delivery

Summary

Review questions

10

Deploying Your Application

Technical requirements

What is involved in publishing a web application?

Domains, Domain Name Servers (DNS), and DNS records

Considerations for building our application for deployment

Web server options and configurations

Apache HTTP Server configuration

Nginx server configuration

Other servers

Transferring your files to the server

Protecting your web application with Let’s Encrypt

Summary

Review questions

11

Bonus Chapter - UX Patterns

Technical requirements

UI design versus UX design

The principles of UI design

Sufficient contrast or distinction between elements

Stimulating repetition and being consistent

Be mindful of alignment and direction

Use proximity and distance to show natural groups

Laws for UI design

Common patterns for data manipulation

HTML input elements

Checkboxes, radios, and toggle switches

Chips, pills, or tags

Common patterns for data visualization

Tooltips

Notification dots, bubbles, marks, or badges

Toast notifications

Carousel or image sliders

Progress bars and spinners

Pagination and infinite scroller

Common patterns for interaction and navigation

Placement of menus

Breadcrumbs

Modal dialogs

Menu icons

Accordion menus

Mega menus

Drop-down menus

Common patterns for content organization

Responsive applications

Home link

Hero section, call to action, and social media icons

Other patterns

Dark patterns

Trick questions

Sneak into the basket

Roach motels

Privacy Zuckering

Preventing price comparison

Misdirection

Hidden costs

Bait and switch

Confirm shaming

Disguised ads

Friendly spam

Summary

Review questions

Appendix: Migrating from Vue 2

A different way to bootstrap and start the application

Register global components, plugins, and so on

The data property is now always a function

There are more reactive options to choose from

Changes to v-model, props, and events

Removed old browser compatibility

Changes in directory and file organization

Changes in the router and state management

New components and other changes

Other breaking changes

Summary

Final words

Index

Other Books You May Enjoy

Preface

Vue 3 is the latest and most performant iteration of the “progressive framework” to create reactive and responsive user interfaces. The framework itself introduces new concepts and approaches to design patterns that could be uncommon in other libraries and frameworks. By learning the basics of the framework and understanding design principles and patterns from software engineering, this book helps you identify the trade-offs of each approach and build solid applications.

It starts with basic concepts and then moves forward through examples and coding scenarios to build incrementally more complex architectures. You will start with a simple page and end with a multithreading, offline, and installable Progressive Web Application (PWA). The content also explores how to use the new test tools available for Vue 3.

Beyond showing you “how things are done,” this book helps you to learn how to “think” and “approach” common problems that design patterns have already found a solution for. Avoiding re-inventing the wheel with every project will save you time and make your software better suited for future changes.

Who this book is for

This book targets Vue developers who care about framework design principles and utilize commonly found design patterns in web application development. Learn to use and configure the new bundler (Vite), Pinia (state management), Router 4, web workers, and other technologies to create performant and solid applications. Prior knowledge of JavaScirpt and basic knowledge of Vue would be beneficial.

What this book covers

Chapter 1, The Vue 3 Framework

What is the Vue 3 progressive framework? This chapter introduces the most important aspects of the framework and other key concepts.

Chapter 2, Software Design Principles and Patterns

Software principles and patterns make up the trademarks of good software architecture. This chapter introduces both, with examples for implementation in JavaScript and Vue 3.

Chapter 3, Setting Up a Working Project

With the necessary introductory concepts in place, this chapter sets up a working project that will be used as the base reference for future projects. It will guide you, step by step, on how to start a project using the right tools.

Chapter 4, User Interface Composition with Components

This chapter introduces the concept of user interfaces and leads you into the implementation of a web application, from the conceptual visual design to the development of components to match it.

Chapter 5, Single-Page Applications

This is a key chapter that introduces the Vue Router to create single-page web applications.

Chapter 6, Progressive Web Applications

This chapter builds on top of SPAs to create PWAs and introduces the use of tools to evaluate their readiness and performance.

Chapter 7, Data Flow Management

This chapter introduces you to key concepts to design and control the flow of data and information within an application and between components. It introduces Pinia as the official state management framework for Vue 3.

Chapter 8, Multithreading with Web Workers

This chapter focuses on improving the performance of a large-scale application using multithreading with web workers. It also introduces more patterns for an easy-to-implement and maintainable architecture.

Chapter 9, Testing and Source Control

In this chapter, we are introduced to the official testing tools provided by the Vue team, as well as the most widespread version control system: Git. The chapter shows how to create test cases for our standalone JavaScript as well as Vue 3 components.

Chapter 10, Deploying Your Application

This chapter presents the necessary concepts to understand how to publish a Vue 3 application on a live production server and how to secure it with a Let’s Encrypt certificate.

Chapter 11, Bonus Chapter - UX Patterns, This bonus chapter expands into the concepts of user interface and user experience patterns, to provide a common language between the developer and designer. It presents the common patterns provided by the HTML 5 standard and other common elements.

Appendix: Migrating from Vue 2 to Vue 3

This appendix provides a guide to changes and migration options for experienced Vue 2 developers.

Final Words

In this final chapter, the author briefly summarizes all the concepts learned in each chapter and encourages you to continue your personal development.

To get the most out of this book

This book assumes that you are familiar with and comfortable with web technologies such as JavaScript, HTML, and CSS. Developers interested in expanding their understanding of design patterns and architecture will get the most out of this book. Students and beginners in the world of web applications can also follow this book by paying careful attention to the code examples and using the provided projects from the GitHub repository.

Software/hardware covered in the book

Operating system requirements

Official Vue 3 ecosystem:

Vue 3 frameworkPiniaVue RouterViteVitestVue Testing Tools

Windows, macOS, or Linux

Node.js (any version + v16 LTS)

Windows, macOS, or Linux

Web servers: NGINX, Apache

Windows or Linux

Visual Studio Code

Windows, macOS, or Linux

Chrome browser

Windows, macOS, or Linux

There are no specific hardware requirements considering modern computers, but it is recommended to have at least the following:

An Intel or AMD CPU of at least 1 GHz4 GB of RAM (more is better)At least 10 GB of available storage (for programs and code)

As a general rule, if your computer can run a modern web browser (Chrome/Chromium, Mozilla Firefox, or Microsoft Edge), then it should meet all the requirements to install and run all the developer tools mentioned in this book.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Vue.js-3-Design-Patterns-and-Best-Practices. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Code in Action

The Code in Action videos for this book can be viewed at https://packt.link/FtCMS

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/oronG.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The main.js file will import and launch the Vue 3 applications.”

A block of code is set as follows:

<script setup>     // Here we write our JavaScript </scrip> <template>     <h1>Hello World! This is pure HTML</h1> </template> <style scoped>     h1{color:purple} </style>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<script> export default{     data(){return {_hello:"Hello World"}} } </script>

Any command-line input or output is written as follows:

$ npm install

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “In this case, it is worth mentioning the Boy Scout Principle, which is similar but applies in groups.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Vue.js 3 Design Patterns and Best Practices, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803238074

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly