Vue.js in Action (Eric Hanchett, Benjamin Listwon) (Z-Library)

Author: Eric Hanchett, Benjamin Listwon

教育

Vue.js is a front-end framework that builds on many of the reactive UI ideas introduced in React.js. Vue.js in Action teaches readers to build fast, flowing web UI with the Vue.js framework. As they move through the book, readers put their skills to practice by building a complete web store application with product listings, a checkout process, and an administrative interface!

📄 File Format: PDF
💾 File Size: 13.3 MB
41
Views
0
Downloads
0.00
Total Donations

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

📄 Page 1
(This page has no text content)
📄 Page 2
Vue.js in Action Erik Hanchett with Benjamin Listwon Playlists History Topics Learning Paths Offers & Deals Highlights Settings Support Sign Out
📄 Page 3
Copyright For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact        Special Sales Department        Manning Publications Co.        20 Baldwin Road        PO Box 761        Shelter Island, NY 11964        Email: orders@manning.com ©2018 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.  Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid­free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20    PO Box 761       History Topics Learning Paths Offers & Deals Highlights Settings Support Sign Out Shelter Island NY 11964,
📄 Page 4
Development editor: Toni Arritola Technical development editor: Doug Warren Review editor: Ivan Martinović Project manager: Lori Weidert Copy editor: Katie Petito Proofreader: Elizabeth Martin Technical proofreader: Jay Kelkar Typesetter and cover designer: Marija Tudor ISBN 9781617294624 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – SP – 23 22 21 20 19 18
📄 Page 5
About this book Before you dive into learning how to make Vue.js applications, let’s talk about a few things you should know first. In this book we’ll look at everything you need to know to become proficient in Vue.js. The goal of the book is to get you the knowledge you need so you can jump into any Vue.js application without hesitation. While doing research for this book, I heard repeatedly that the official Vue.js guides were the best resource for learning Vue.js. While the official guides are great, and I highly recommend you check them out as additional references while you learn Vue.js, they don’t cover everything, and they’re not perfect. As I wrote the book, I took it upon myself to go beyond what the official guides covered. I made the examples more understandable and relatable, so you could more easily adapt the concepts to your own projects. Where I thought a topic was beyond the scope of the book, or not important enough, I added a reference where you can learn more about it inside the official guides. This book can be used in a couple of different ways. You can read it from front to back. In that instance, you’ll get the full breadth of what Vue.js has to offer. Or you can use this book as a reference manual to look up whatever concept you need more information on. Either way is acceptable and fine. Later in the book we’ll transition to creating Vue.js apps using a build system. Don’t worry, I’ve included instructions on how to get started with a Vue.js build tool called Vue­CLI in appendix A. One of the most important benefits of Vue­CLI is that it helps us create more complex Vue.js applications without having to worry about building or transpiling our code. Throughout the book we’ll create a Vue.js pet store application. Certain chapters use the pet store example more than others. I did this on purpose, so you could easily learn a concept without having to learn how it works with the pet store app. But people who prefer to learn with a real application still have that option. AUDIENCE History Topics Lear ing Paths Offers & Deals Highlights Settin s Support Sign Out
📄 Page 6
AUDIENCE This book is for anyone who’s interested in learning Vue.js and has JavaScript, HTML, and CSS experience. I don’t expect you to have much knowledge on this but knowing the basics, such as arrays, variables, loops, and HTML tags will help. As for CSS, we’ll use Bootstrap 3, a CSS library. However, you don’t need to know anything about Bootstrap to follow along with the examples. It’s only there to help with styling. Early in the book, I introduce the example code using ECMAScript 2015, otherwise known as ES6. It would be a good idea to look it over before you start this book. For the most part, I use only a few ES6 features, such as arrow functions and ES6 imports. I’ll warn you in the book when we make this transition. ROADMAP The book is broken into three parts, each building upon the previous one. Part 1 is keyed toward getting to know Vue.js. In chapters 1 and  2  we’ll create our first Vue.js application. We’ll look at what a Vue.js instance is and how it relates to our application. In part 2, chapters 3– 9 , we’ll look more closely at the View and ViewModel. In this section we dive into several of the meatiest parts of Vue.js. Part 1 is more of an appetizer to Vue.js, while part 2 is the main course. You’ll learn the intricacies of how to create a Vue.js application. We’ll begin by learning the reactive model, and we’ll create a pet store application that we’ll use throughout the rest of the book. We’ll add in forms and inputs and how to bind information using Vue.js’s powerful directives, then look at conditionals, looping, and forms. Chapters 6 and  7  are extremely important. We’ll learn how to break a Vue.js app into several logical parts using components, and we’ll have a first look at the build tools you’ll need to create Vue.js apps. Chapter 7 also covers routing. In earlier chapters, we use simple conditionals to navigate our application. With the addition of routing, we can properly move around our application and pass information between routes. Chapter 8 introduces you to the powerful animations and transitions you can perform using Vue.js. These features are baked into the language and are nice features you should check out.
📄 Page 7
In chapter 9 we’ll learn how to use mixins and custom directives to easily extend Vue without repeating ourselves. Part 3 is all about modeling data, consuming APIs, and testing. In chapters 10 and 11, we begin with a deep dive into Vue’s state management system called Vuex. We’ll then look at how we can start communicating to a backend server, and we’ll learn more about Nuxt.js, a server­side rendered framework. Chapter 12 is dedicated to testing. In any professional environment, you’ll need to know testing, and we’ll look at the essentials you must know. BOOK FORUM Purchase of Vue.js in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://forums.manning.com/forums/vue­js­in­action. You can also learn more about Manning’s forums and the rules of conduct at https://forums.manning.com/forums/about. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. SOURCE CODE This book contains many examples of source code, both in numbered listings and inline with normal text. In both cases, source code is formatted in a fixed­width font like this to separate it from ordinary text. Sometimes boldface is used to highlight code that has changed from previous steps in the chapter, such as when a new feature is added to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line­continuation markers ( ). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts.
📄 Page 8
The source code for this book is available to download from the publisher’s website (www.manning.com/books/vue­js­in­action) and from my personal GitHub repository (https://github.com/ErikCH/VuejsInActionCode). You can also find more instructions on downloading the code and setting up your programming environment in appendix A. While going through the book, you’ll notice I often split the source code into separate files. I’ve included both the completed file and the separated files in each chapter with the source code, so you can follow along. If you find a bug in the code, feel free to send over a pull request to my GitHub. I’ll maintain the repo, and I’ll leave a comment in the readme with any updates. SOFTWARE REQUIREMENTS To make things easy, all the code in this book will work on any modern browser. I’ve tested it personally on Firefox 58, Chrome 65, and Microsoft Edge 15. I wouldn’t recommend trying to run any of my apps on older browsers, because you’ll certainly run into problems. Vue.js itself doesn’t support IE8 and below. It must have a ECMAScript 5 compliant browser. In several of the earlier chapters, I use a few ES6 features. You’ll need to have a modern web browser to run those examples. The pet store app we’ll create throughout the book will work on a mobile browser. However, the pet store application isn’t optimized for mobile, so I recommend you run the examples on a desktop computer. You don’t have to worry about your operating system. If the web browser runs, you should be fine. There are really no other requirements. ONLINE RESOURCES As I mentioned earlier, the Vue.js official guides are great to use as references while you’re working the examples in the book. You can find the guides at https://vuejs.org/v2/guide/. They’re continually being updated. There’s a curated list of awesome things related to Vue.js on the GitHub page https://github.com/vuejs/awesome­vue. Here, you can find links to Vue.js podcasts, additional Vue.js resources, third­party libraries, and even companies that use Vue.js. I highly recommend checking it out. The Vue.js community is huge and is continuously growing. One of the best places to talk to other Vue.js developers is the official Vue.js forum at https://forum.vuejs.org/. Here
📄 Page 9
you can discuss or get help on anything Vue. If you’re looking for more video tutorials, my channel, http://erik.video on YouTube, covers a ton of information on Vue.js and JavaScript in general. Check it out! MORE INFO? In this 300­page book I cover a large amount of material. Please, don’t hesitate to reach out to me, the author, if you’re getting stuck, or you need help. If I can’t help you, I’ll at least point you in the right direction. Don’t be shy. You’ll find those of us in the Vue.js community are approachable to beginners. Also, as you go through the book, try to take several of the concepts you learn and implement them yourself. One of the best ways of learning is doing. For example, instead of following along with the pet store app, try to create your own ecommerce site. Use the book as guide rails to make sure you don’t get stuck. One last thing: have fun. Be creative and make something cool. Make sure to hit me up on twitter @ErikCH if you do!
📄 Page 10
Part 1. Getting to know Vue.js Before we can learn all the cool things Vue has to offer, we need to get to know it first. In these first two chapters, we’ll look at the philosophy behind Vue.js, the MVVM pattern, and how it relates to other frameworks. Once we understand where Vue is coming from, we’ll look deeper at the Vue instance. The root Vue instance is the heart of the application, and we’ll explore how it’s structured. Later, we’ll look at how we can bind data in our application to Vue. These chapters will give you a great start in Vue.js. You’ll learn how to create a simple app and how Vue works. Playlists History Topics Learning Paths Offers & Deals Highlights Settings Support Sign Out
📄 Page 11
Chapter 1. Introducing Vue.js This chapter covers Exploring the MVC and MVVM design patterns Defining a reactive application Describing the Vue lifecycle Evaluating the design of Vue.js Interactive websites have been around for a long time. During the beginning of the Web 2.0 days in the mid­2000s, a much larger focus was put on interactivity and engaging users. Companies such as Twitter, Facebook, and YouTube were all created during this time. The rise of social media and user­generated content was changing the web for the better. Developers had to keep up with these changes to allow more interactivity for the end user and early on, libraries and frameworks started making interactive websites easier to build. In 2006, jQuery was released by John Resig, greatly simplifying the client­side scripting of HTML. As time progressed, client­side frameworks and libraries were created. At first these frameworks and libraries were big, monolithic, and opinionated. Now, we’ve seen a shift to smaller, lighter­weight libraries that can be easily added to any project. This is where Vue.js comes in. Vue.js is a library that enables us to add that interactive behavior and functionality to any context where JavaScript can run. Vue can be used on individual webpages for simple tasks or it can provide the foundation for an entire enterprise application. Tip The terms Vue and Vue.js are used somewhat interchangeably around the web. Throughout the book, I use the more colloquial Vue for the most part, reserving Vue.js Playlists History Topics Learning Paths Offers & D als Highlights Settings Support Sign Out
📄 Page 12
for when I’m referring specifically to the code or the library. From the interface that visitors interact with to the database that provides our application with its data, we’ll explore how Vue and its supporting libraries enable us to build complete, sophisticated web applications. Along the way, we’ll examine how each chapter’s code fits into the bigger picture, what industry best practices are applicable, and how you can incorporate what we’re working on into your own projects, both existing and new. This book is primarily written for web developers who have a moderate degree of JavaScript familiarity and a healthy understanding of HTML and CSS. That said, owing much to the versatility of its application programming interface (API), Vue is a library that grows with you as a developer as it grows with your project. Anyone who wants to build a prototype or an app for a personal side project should find this book a reliable guide on that journey. 1.1. ON THE SHOULDERS OF GIANTS Before we write any code for our first application, or even dig into Vue at a high level, it’s important to understand a little bit of software history. It’s difficult to truly appreciate what Vue does for us without knowledge of the problems and challenges that web applications have faced in the past and what advantages Vue brings to the table. 1.1.1. The Model–View–Controller pattern A testament to its utility, the client­side Model–View–Controller (MVC) pattern provides the architectural blueprint used by many modern web application development frameworks. (If you’re familiar with MVC, feel free to skip ahead.) It’s worth mentioning before we continue that the original MVC design pattern has changed throughout the years. Sometimes known as Classic MVC, it involved a separate set of rules on how the view, controller, and model interacted. For the sake of simplicity, we’ll discuss a simplified version of the client­side MVC pattern. This pattern is a more modern interpretation for the web. As you can see in figure 1.1, the pattern is used to separate the application’s concerns. The view is responsible for displaying information to the user. This represents the graphical user interface (GUI). The controller is in the middle. It helps transform events from the view to the model and data from the model to the view. Finally, the
📄 Page 13
model holds business logic and could contain a kind of datastore. Figure 1.1. The roles of the model, view, and controller as described by the MVC pattern. Info If you’re interested in learning more about the MVC pattern, start with Martin Fowler’s page on the evolution of MVC at https://martinfowler.com/eaaDev/uiArchs.html. Many web framework authors have used a variation of this MVC pattern because of its solid, time­tested architecture. If you want to know more about how modern web frameworks are designed and architected, check out SPA Design and Architecture by Emmitt A. Scott Jr. (Manning, 2015). In modern software development, the MVC pattern is often used as a part of a single application and provides a great mechanism for separating the roles of application code. For websites using the MVC pattern, every request initiates a flow of information from the client to the server, then the database, and all the way back again. That process is time­consuming, resource­intensive, and doesn’t provide a responsive user experience. Over the years, developers have increased the interactivity of web­based applications by using asynchronous web requests and client­side MVC so that requests sent to the server are non­blocking and execution continues without a reply. But as web applications begin to function more like their desktop counterparts, waiting for any client/server interaction can make an application feel sluggish or broken. That’s where our next pattern comes to the rescue.
📄 Page 14
A word about business logic You’ll find a good degree of flexibility in the client­side MVC pattern when considering where business logic should be implemented. In figure 1.1 we consolidated the business logic in the model for simplicity’s sake, but it may also exist in other tiers of the application, including the controller. The MVC pattern has changed since it was introduced by Trygve Reenskaug in 1979 for Smalltalk­76. Consider the validation of a ZIP Code provided by a user: The view might contain JavaScript that validates a ZIP Code as it’s entered or prior to submission. The model might validate the ZIP Code when it creates an address object to hold the incoming data. Database constraints on the ZIP Code field may mean that the model is also enforcing business logic, although this could be considered bad practice. It can be difficult to define what constitutes actual business logic, and in many cases, all the previous constraints may come into play within a single request. As we build our application in this book, we’ll examine how and where we’re organizing our business logic, as well as how Vue and its supporting libraries can help keep functionality from bleeding across boundaries. 1.1.2. The Model–View–ViewModel pattern When JavaScript frameworks began to support asynchronous programming techniques, web applications were no longer required to make requests for complete web pages. Websites and applications could respond faster with partial updates to the view, but doing so required a degree of duplicated effort. Presentation logic often mirrored business logic. A refinement of MVC, the primary difference in the Model–View–ViewModel (MVVM) pattern is the introduction of the view­model, and its data bindings (collectively, the binder). MVVM provides a blueprint for us to build client­side applications with more responsive user interaction and feedback, while avoiding costly duplication of code and effort across the overall architecture. It’s also easier to unit test. With that said, MVVM may be overkill for simple UIs, so take that into consideration.
📄 Page 15
For web applications, the design of MVVM allows us to write software that responds immediately to user interaction and allows users to move freely from one task to the next. As you can see from figure 1.2, the view­model also wears different hats. This consolidation of responsibility has a single, profound implication for our application’s views: when data changes in the view­model, any view bound to it is automatically updated. The data binder exposes data and helps guarantee that when data changes, it’s reflected in the view. Info You can find more information on the MVVM pattern on Martin Fowler’s page on the Presentation model at https://martinfowler.com/eaaDev/PresentationModel.html. Figure 1.2. The components of the Model–View–ViewModel pattern. 1.1.3. What’s a reactive application? The reactive programming paradigm isn’t necessarily a new idea. Its adoption by web applications is relatively new and owes much to the availability of JavaScript frameworks such as Vue, React, and Angular. Many great resources on reactive theory are available on the web, but our needs are perhaps a bit more focused. For a web application to be thought of as reactive, it should do the following: Observe changes in application state
📄 Page 16
Propagate change notification throughout the application Render views automatically in response to changes in state Provide timely feedback for user interactions Reactive web applications accomplish these goals by employing MVVM design principles using asynchronous techniques to avoid blocking continued interaction and using functional programming idioms where possible. While the MVVM pattern doesn’t imply a reactive application and vice versa, they share a common intention: to provide a more responsive, reliable experience to the users of an application. Superman and Clark Kent may present themselves differently, but they both want to do right by humanity. (No, I won’t say which of MVVM and Reactive I think wears the cape and which the glasses.) Info If you’d like to learn more about Vue’s reactive programming paradigm, check out the Reactivity in Depth guide at https://vuejs.org/v2/guide/reactivity.html. 1.1.4. A JavaScript calculator To better understand the notions of data binding and reactivity, we’ll start by implementing a calculator in plain, vanilla JavaScript, as shown in this listing. Listing 1.1. The JavaScript calculator: chapter-01/calculator.html <!DOCTYPE> <html>   <head>     <title>A JavaScript Calculator</title>     <style>      p, input { font­family: monospace; }      p, { white­space: pre; }     </style>   </head>   <!­­ Bind to the init function ­­>   <body>     <div id="myCalc">                                                1       <p>x <input class="calc­x­input" value="0"></p>       <p>y <input class="calc­y­input" value="0"></p>       <p>­­­­­­­­­­­­­­­­­­­­</p>          <p>= <span class="calc­result"></span></p>                  2
📄 Page 17
    </div>     <script type="text/javascript">      (function(){        function Calc(xInput, yInput, output) {                       3          this.xInput = xInput;          this.yInput = yInput;          this.output = output;        }        Calc.xName = 'xInput';        Calc.yName = 'yInput';        Calc.prototype = {          render: function (result) {            this.output.innerText = String(result);          }        };        function CalcValue(calc, x, y) {                              4          this.calc = calc;          this.x = x;          this.y = y;          this.result = x + y;        }        CalcValue.prototype = {          copyWith: function(name, value) {            var number = parseFloat(value);            if (isNaN(number) || !isFinite(number))              return this;            if (name === Calc.xName)              return new CalcValue(this.calc, number, this.y);            if (name === Calc.yName)              return new CalcValue(this.calc, this.x, number);            return this;          },          render: function() {            this.calc.render(this.result);          }        };        function initCalc(elem) {                                     5          var calc =            new Calc(              elem.querySelector('input.calc­x­input'),              elem.querySelector('input.calc­y­input'),              elem.querySelector('span.calc­result')            );
📄 Page 18
         var lastValues =            new CalcValue(              calc,              parseFloat(calc.xInput.value),              parseFloat(calc.yInput.value)            );          var handleCalcEvent =                                       6            function handleCalcEvent(e) {              var newValues = lastValues,                  elem = e.target;              switch(elem) {                case calc.xInput:                  newValues =                    lastValues.copyWith(                      Calc.xName,                      elem.value                    );                  break;                case calc.yInput:                  newValues =                    lastValues.copyWith(                      Calc.yName,                      elem.value                    );                  break;              }              if(newValues !== lastValues){                lastValues = newValues;                lastValues.render();              }            };          elem.addEventListener('keyup', handleCalcEvent, false);     7          return lastValues;        }        window.addEventListener(          'load',          function() {            var cv = initCalc(document.getElementById('myCalc'));            cv.render();          },          false        );      }());     </script>   </body> </html>
📄 Page 19
1 Forms input to collect x and y that bind to the runCalc function 2 Shows results of x and y 3 Shows constructor to create calc instance 4 Shows constructor to create values for a calc instance 5 Initializes calc component 6 Shows the event handler 7 Sets the event listener on keyup This is a calculator using ES5 JavaScript (we’ll use the more modern version of JavaScript ES6/2015 later in the book). We’re using an immediately invoked function expression that kicks off our JavaScript. A constructor is used to hold values and the handleCalcEvent event handler fires on any keyup. 1.1.5. A Vue calculator Don’t worry too much about the syntax of the Vue example because our goal here isn’t to understand everything going on in the code, but to compare the two implementations. That said, if you have a good sense of how the JavaScript example works (as shown in the following listing), much of the Vue code should make sense at least on a theoretical level. Listing 1.2. The Vue calculator: chapter-01/calculatorvue.html <!DOCTYPE html> <html> <head>   <title>A Vue.js Calculator</title>   <style>     p, input { font­family: monospace; }     p { white­space: pre; }   </style> </head> <body>   <div id="app">                                                1     <p>x <input v­model="x"></p>                                2     <p>y <input v­model="y"></p>     <p>­­­­­­­­­­­­­­­­­­­­­</p>     <p>= <span v­text="result"></span></p>                      3   </div>   <script src="https://unpkg.com/vue/dist/vue.js"></script>     4   <script type="text/javascript">   function isNotNumericValue(value) {     return isNaN(value) || !isFinite(value);
📄 Page 20
  }     var calc = new Vue({                                        5       el: '#app',                                               6       data: { x: 0, y: 0, lastResult: 0 },                      7       computed: {                                               8         result: function() {             let x = parseFloat(this.x);             if(isNotNumericValue(x))               return this.lastResult;             let y = parseFloat(this.y);             if(isNotNumericValue(y))               return this.lastResult;             this.lastResult = x + y;             return this.lastResult;         }       }     });   </script> </body> </html> 1 Shows the DOM anchor for our app 2 Shows the form inputs for the application 3 Results will show up in this span. 4 Lists the script tag that adds the Vue.js library 5 Initializes the application 6 Connects to the DOM 7 Shows the variables added to the app 8 Calculation is done here using a computed property. 1.1.6. Comparison of JavaScript and Vue The code for both calculator implementations is, for the most part, different. Each sample shown in figure 1.3 is available in the repository that accompanies this chapter, so you can run each one and compare how they operate. Figure 1.3. Side-by-side comparison of a reactive calculator written using vanilla JavaScript (on the left) and Vue (on the right).
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List