Statistics
59
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-11-22

AuthorMaya Shavin

Learn the core concepts of Vue.js, the modern JavaScript framework for building frontend applications and interfaces from scratch. With concise, practical, and clear examples, this book takes web developers step-by-step through the tools and libraries in the Vue.js ecosystem and shows them how to create complete applications for real-world web projects. You'll learn how to handle data communication between components with Pinia architecture, develop a manageable routing system for a frontend project to control the application flow, and produce basic animation effects to create a better user experience. This book also shows you how to: Create reusable and lightweight component systems using Vue.js Bring reactivity to your existing static application Set up a project using Vite.js, a build tool for frontend project code management Build an interactive state management system for a frontend application with Pinia Connect external...

Tags
No tags
Publisher: O'Reilly Media
Publish Year: 2023
Language: 中文
Pages: 498
File Format: PDF
File Size: 19.5 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Learning Vue Core Concepts and Practical Patterns for Reusable, Composable, and Scalable User Interfaces Maya Shavin
Learning Vue by Maya Shavin Copyright © 2024 Maya Shavin. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Amanda Quinn Development Editor: Michele Cronin Production Editor: Ashley Stussy Copyeditor: Piper Editorial Consulting, LLC Proofreader: Liz Wheeler Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea December 2023: First Edition Revision History for the First Edition 2023-12-01: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781492098829 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Vue, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-492-09882-9 [LSI]
Preface The JavaScript framework plays a significant role in modern web frontend development. When developing web projects, companies choose a framework for various reasons, including the quality of the final product, the cost of development, coding standard, and ease of development. Hence, learning to work with a JavaScript framework, such as Vue, is essential for any modern web developer (or frontend developer or full stack developer). This book is for programmers who want to learn and develop Web applications using Vue library, in JavaScript and TypeScript, from end to end. It focuses solely on how Vue and its ecosystem can help you build scalable and interactive web applications in the most straightforward and comfortable direction. While covering the basics, we will also get into Vue Router and Pinia for state management, testing, animation, deployment, and server-side rendering, making sure you are ready to move on and start developing complex Vue projects right away. It’s OK if you are not familiar with Vue or the concept of Virtual DOM. This book doesn’t assume any prior knowledge of Vue or any similar framework. I will introduce and guide you through all Vue’s basics from scratch. I will also walk you through the Virtual DOM concept and reactivity system in Vue in Chapter 2, as the foundation for the rest of the book. This book doesn’t require you to know TypeScript, though you will be better prepared if you are familiar with TypeScript basics. You will also be better prepared for the contents of the book if you have prior basic knowledge of HTML, CSS, and JavaScript. A solid foundation of these three is always crucial before diving to any web (or frontend) Javascript framework. Conventions Used in This Book
The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP This element signifies a tip or suggestion. NOTE This element signifies a general note. WARNING This element indicates a warning or caution.
Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/mayashavin/learning-vue-app. If you have a technical question or a problem using the code examples, please send email to bookquestions@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Learning Vue by Maya Shavin (O’Reilly). Copyright 2024 Maya Shavin, 978-1-492-09882-9.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed.
Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit http://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-889-8969 (in the United States or Canada) 707-829-7019 (international or local) 707-829-0104 (fax) support@oreilly.com https://www.oreilly.com/about/contact.html We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/learning- vue-1e. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media
Follow us on Twitter: https://twitter.com/oreillymedia Watch us on YouTube: https://youtube.com/oreillymedia Acknowledgments As I embarked on the journey of writing this book, my family was navigating a tumultuous period, full of highs and lows. Despite enjoying every moment, writing this book required a lot of time, effort, and dedication, and I wouldn’t be able to commit to it without the support from my family, particularly my husband, Natan. His encouragement, belief in my programming skills, humor about frontend development, parenting our children during my work travels, lending an ear to my daily grievances, and helping me balance work with personal life have been invaluable. Without Natan, I would not be where I am today. Just as quality code demands thorough review, this book’s excellence owes much to critical technical insights and encouragement from Jakub Andrzejewski, Chris Fritz, Lipi Patnaik, Edward Wong, and Vishwesh Ravi Shrimali. Your valuable feedback has been pivotal in sharpening my focus and elevating the quality of this work. My heartfelt appreciation goes to my O’Reilly team: Zan McQuade and Amanda Quinn, for guiding me through the acquisition process of Learning Vue, and to my exceptional editor, Michele Cronin. Michele, your insightful feedback, professionalism, and empathy, particularly during the challenging final stages of the book, were extraordinary. The production editing skills of Ashley Stussy and the copyediting expertise of Beth Richards were crucial in elevating my manuscript to production quality. This book wouldn’t have materialized as envisioned without your collective efforts. I extend a special thank you to the Vue core team for developing such a great framework and ecosystem, and to the Vue community members and friends for their support and inspiration. The knowledge and insights I gained from you are immeasurable and continue to enrich me daily.
Finally, my profound gratitude to you, the readers. Choosing this book from the plethora of resources available, including countless videos and tutorials, demonstrates a trust in my work that I deeply appreciate. I hope Learning Vue serves as a valuable tool in your journey, whether you aspire to be a web, frontend, or full-stack developer. Thank you, from the bottom of my heart. And remember, in the world of web development, always “react with a Vue.”
Chapter 1. Welcome to the Vue.js World! Initially released in 2014, Vue.js has experienced rapid adoption, especially in 2018. Vue is a popular framework within the developer community, thanks to its ease of use and flexibility. If you are looking for a great tool to build and ship excellent performant web applications to end users, Vue.js is the answer. This chapter highlights the core concepts of Vue.js and walks you through the tools you need for your Vue.js development environment. It also explores helpful tools that make your Vue.js development process more manageable. By the end of the chapter, you will have a working environment with a simple Vue.js application ready to start your journey in learning Vue.js. What Is Vue.js? Vue.js, or Vue, means view in French; it is a JavaScript engine for building progressive, composable, and reactive user interfaces (UI) in frontend applications. NOTE We will use the term Vue to indicate Vue.js from this point on. Vue is written on top of JavaScript and offers an organized mechanism to structure and build a web application. It also acts as the trans-compiler (transpiler) that compiles and translates Vue code (as a Single File Component, which we will discuss further in “Vue Single File Component
Structure”) into equivalent HTML, CSS, and JavaScript code in build time before deploying. In a standalone mode (with a generated script file), the Vue engine performs the code translation at run-time instead. Vue follows the MVVM (Model–View–ViewModel) pattern. Unlike MVC (Model–View–Controller),1 the ViewModel is the binder that binds data between the View and Model. Allowing direct communication for the view and model progressively enables the component’s reactivity. In short, Vue was created to focus only on the View layer but is incrementally adaptable to integrate with other external libraries for more complex usage. Since Vue focuses solely on the View layer, it empowers the development of single-page applications (SPAs). SPAs can move quickly and fluidly while communicating data continuously with the backend. The official website for Vue includes API documentation, installation, and primary use cases for reference. The Benefits of Vue in Modern Web Development A significant advantage of Vue is its well-written, easy-to-understand documentation. In addition, the ecosystem and supporting community built around Vue, such as Vue Router, Vuex, and Pinia, helps developers set up and run their projects with minimum effort. Vue APIs are straightforward and familiar to anyone who has worked with AngularJS or jQuery before. Its powerful template syntax minimizes the learning effort required and makes it easier to work with data or listen to Document Object Model (DOM) events in your application. Another significant benefit Vue offers is its size. The size of a framework is a substantial aspect of the application’s performance, especially the initial loading time on delivery. At the time of writing, Vue stands as the fastest and most lightweight framework (~10kB in size). This advantage results in
less time-consuming downloading and better run-time performance from a browser perspective. With the release of Vue 3, the built-in support for TypeScript now offers developers the benefit of typing in types and making their codebase more readable, organized, and maintainable in the long term. Installing Node.js Working with Vue requires setting up the development ecosystem and prior coding knowledge to keep up with the learning process. Node.js and NPM (or Yarn) are necessary development tools to install before you start working on any application. Node.js (or Node) is an open source JavaScript server environment built on Chrome’s V8 JavaScript run-time engine. Node allows developers to code and run JavaScript applications locally or in a hosted server, outside a browser. NOTE Chromium-based browsers like Chrome and Edge also use the V8 engine to interpret JavaScript code into efficient low-level computer code and execute it. Node is cross-platform supported and easy to install. If you are not sure you installed Node, open your terminal (or command prompt in Windows) and run the following command: node -v The output should be a Node version or “Command not found” if Node is not installed. If you haven’t installed Node, or your Node version is lower than 12.2.0, please visit the Node project website and download the installer for the
latest version based on your operation system (Figure 1-1). Once the download finishes, click on the installer and follow the instructions to set it up. When installing Node, besides the node command, you also have the npm command added to the command-line tool. If you type the node -v command, you should see the installed version number displayed. Figure 1-1. Latest version for download in Node’s official website NPM The Node Package Manager (NPM) is the default package manager for Node. It will be installed together with Node.js by default. It lets developers download and install other remote Node packages with ease. Vue and other frontend frameworks are examples of helpful Node packages.
NPM is a powerful tool for developing complex JavaScript applications, with the ability to create and run task scripts (to start a local development server, for instance) and automatically download project package dependencies. Similar to the Node version check, you can perform an NPM version check through the npm command: npm -v To update your NPM version, use the following command: npm install npm@latest -g With parameter @latest, your current NPM tool automatically updates its version to the latest version. You can run npm -v again to ensure it is updated correctly. You can also replace the latest word to target any specific NPM version (in the format xx.x.x). Additionally, you need to indicate the installation at the global scope with the -g flag for the npm command to be available everywhere on your local machine. For example, if you run the command npm install npm@6.13.4 -g, the tool will target the NPM package version 6.13.4 for installing and updating. NPM VERSION FOR THIS BOOK I recommend installing NPM version 7.x to be able to follow all the NPM code examples in this book. A Node project depends on a collection of Node packages2 (or dependencies) to be up and running. In the package.json file within the project directory, you can find these installed packages. This package.json file also describes the project, including the name, author(s), and other scripting commands applied to the project exclusively.
When you run the command npm install (or npm i) within the project folder, NPM will refer to this file and install all the listed packages into a folder called node_modules, ready for the project to use. Also, it will add a package-lock.json file to keep track of the package installed version and compatibility between common dependencies. To start a project from scratch with dependencies, use the following command within the project directory: npm init This command walks you through some questions related to the project and initializes an empty project with a package.json file containing your answers. You can search for any public open source packages at the NPM official website. Yarn If NPM is the standard package manager tool, then Yarn is an alternative and popular package manager developed by Facebook.3 Yarn is faster, more secure, and more reliable due to its parallel downloading and caching mechanism. It is compatible with all NPM packages; thus it can be used as a drop-in replacement for NPM. You can install the latest version of Yarn based on your operating system by visiting the Yarn official website. If you are working on a macOS computer and have Homebrew installed, you can install Yarn directly using the command: brew install yarn This command installs Yarn and Node.js (if not available) globally. You can also install Yarn globally using the NPM package management tool with the following command:
npm i -g yarn You should now have Yarn installed on your machine and ready to use. To check if Yarn is installed and to verify its version, use the following command: yarn -v To add a new package, use the following command: yarn add <node package name> To install the dependencies for a project, instead of npm install, you only need to run the yarn command within the project directory. Once this finishes, similar to NPM, Yarn will also add a yarn.lock file in your project directory. NOTE We will use Yarn as our package manager tool for the code presented in this book. At this point, you have set up your essential coding environment for Vue development. In the next section, we’ll look at the Vue Developer Tools and what they offer us in working with Vue. Vue Developer Tools Vue Developer Tools (or Vue Devtools) are the official tools to help you work with your Vue projects locally. These tools include extensions for Chrome and Firefox, and an Electron desktop application for other browsers. You should install one of these tools during the development process.
Chrome users can head to the extension link in the Chrome Web Store and install the extension, as shown in Figure 1-2. Figure 1-2. Vue Devtools extension page for Chrome For Firefox, you can use the extension link from the Firefox Add-on page, shown in Figure 1-3.
Figure 1-3. Vue Devtools extension page for Firefox Once your extension is installed and enabled, you can detect if any site currently uses Vue in production. When a site is built with Vue, the Vue icon on the browser toolbar highlights as shown in Figure 1-4. Figure 1-4. Icon confirms the Vue official site is built with Vue The Vue Devtools enable you to inspect the Vue component tree, component props and data, events, and routing information within the browser’s developer console. Vue Devtools divide the information into various tabs, providing helpful insights for debugging and inspecting behaviors of any Vue component within the project.
Vite.js as a Builder Management Tool Introduced in 2020, Vite.js (or Vite) is a JavaScript development server that uses the native ES module4 import during development instead of bundling your code into chunks of JavaScript files like Webpack, Rollup, etc. NOTE We will use the term Vite to indicate Vite.js from this point on. This approach allows Vite to perform a hot reload5 during development at an insane speed, making the development experience seamless. It also offers many out-of-the-box features such as TypeScript support and on- demand compilation, which is quickly gaining popularity and adaption among the developer community. The Vue community has replaced the Vue CLI tool6 (which uses Webpack under the hood) with Vite to be the default builder tool for creating and managing Vue projects. Create a New Vue Application With Vite, there are various ways to create a new Vue application project. The most straightforward way is to use the following command syntax in your command prompt or terminal: npm init vue@latest This command will first install create-vue, an official scaffolding tool, and then present you with a list of essentials questions to configure your Vue application. As shown in Figure 1-5, the configurations used for the Vue application in this book include: