vue

未分類 ||

The Majesty of Vue.js 2
Alex Kyriakidis, Kostas Maniatis and Evan You This book is for sale at http://leanpub.com/vuejs2
This version was published on 2017-03-31
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.
© 2016 – 2017 Alex Kyriakidis, Kostas Maniatis and Evan You

Tweet This Book!
Please help Alex Kyriakidis, Kostas Maniatis and Evan You by spreading the word about this book on Twitter!
The suggested tweet for this book is:
I’m learning @vuejs with @tmvuejs. Get it at https://leanpub.com/vuejs2 #vuejs The suggested hashtag for this book is #vuejs2.
Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter:
https://twitter.com/search?q=#vuejs2
Contents
Introduction………………………………… i
AboutVue.js…………………………………….. ii Vue.jsOverview…………………………………. ii WhatpeoplesayaboutVue.js…………………………… ii ComparisonwithOtherFrameworks……………………….. iv
Angular1 …………………………………. iv Angular2 …………………………………. v React……………………………………. vi Ember ……………………………………viii Polymer ………………………………….. ix Riot…………………………………….. x
Welcome………………………………………. xi AbouttheBook …………………………………. xi WhoisthisBookfor……………………………….. xi GetInTouch…………………………………… xi Homework……………………………………. xii SampleCode…………………………………… xii Errata………………………………………. xii Conventions…………………………………… xii
I Vue.jsFundamentals……………………… 1 1. InstallVue.js…………………………………… 2
1.1
1.2 1.3
StandaloneVersion ……………………………. 2 1.1.1 Downloadfromvuejs.org ………………………. 2 1.1.2 IncludefromCDN………………………….. 2
DownloadusingNPM…………………………… 3 DownloadusingBower………………………….. 3
2. GettingStarted …………………………………. 4 2.1 HelloWorld ……………………………….. 4 2.2 Two-wayBinding…………………………….. 6
CONTENTS
2.3 ComparisonwithjQuery………………………….. 7 2.4 Homework………………………………… 9
3. AFlavorofDirectives………………………………. 10
3.1 3.2
3.3 3.4 3.5
v-show………………………………….. 10
v-if……………………………………. 13 3.2.1 Templatev-if…………………………….. 14 v-else…………………………………… 15 v-ifvs.v-show………………………………. 18 Homework………………………………… 19
4. ListRendering………………………………….. 20
4.1 4.2
4.3
4.4 4.5
Install&UseBootstrap ………………………….. 20
v-for…………………………………… 22 4.2.1 Rangev-for……………………………… 22 ArrayRendering……………………………… 23 4.3.1 LoopThroughanArray ……………………….. 23 4.3.2 LoopThroughanArrayofObjects ………………….. 25 Objectv-for ……………………………….. 28 Homework………………………………… 30
5. Interactivity…………………………………… 31
5.1 EventHandling ……………………………… 31 5.1.1 HandlingEventsInline………………………… 31 5.1.2 HandlingEventsusingMethods……………………. 33 5.1.3 Shorthandforv-on………………………….. 34
5.2 EventModifiers ……………………………… 35
5.3 KeyModifiers ………………………………. 39
5.4 ComputedProperties …………………………… 40
5.5 Homework………………………………… 46
6. Filters ……………………………………… 48
6.1
6.2 6.3 6.4 6.5
FilteredResults ……………………………… 48 6.1.1 UsingComputedProperties ……………………… 51 OrderedResults ……………………………… 58 CustomFilters………………………………. 62 UtilityLibraries ……………………………… 63 Homework………………………………… 67
7. Components…………………………………… 68 7.1 WhatareComponents?………………………….. 68 7.2 UsingComponents ……………………………. 68 7.3 Templates ………………………………… 70 7.4 Properties ………………………………… 71
CONTENTS
7.5 Reusability………………………………… 74 7.6 Altogether………………………………… 78 7.7 Homework………………………………… 85
8. CustomEvents …………………………………. 86
8.1 EmitandListen ……………………………… 86 8.1.1 LifecycleHooks …………………………… 88
8.2 Parent-ChildCommunication……………………….. 89
8.3 PassingArguments ……………………………. 91
8.4 NonParent-ChildCommunication…………………….. 96
8.5 RemovingEventListeners…………………………. 99
8.6 Backtostories………………………………. 100
8.7 Homework………………………………… 103
9. ClassandStyleBindings……………………………..105
9.1 9.2
9.3 9.4
Classbinding ………………………………. 105 9.1.1 ObjectSyntax ……………………………. 105 9.1.2 ArraySyntax…………………………….. 108
Stylebinding……………………………….. 110 9.2.1 ObjectSyntax ……………………………. 110 9.2.2 ArraySyntax…………………………….. 111
BindingsinAction…………………………….. 112 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
II ConsuminganAPI……………………….116
10. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 10.1 CRUD …………………………………..117 10.2 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.2.1DownloadBook’sCode ……………………….. 118 10.2.2APIEndpoints ……………………………. 120
11.Workingwithrealdata ……………………………..122
11.1 GetDataAsynchronous………………………….. 122
11.2 Refactoring………………………………… 125
11.3 UpdateData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
11.4 DeleteData ………………………………..130
12. Integrating vue-resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 12.1 Overview …………………………………133 12.2 Migration …………………………………134 12.3 EnhancingFunctionality …………………………. 135
12.3.1 Edit Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
CONTENTS
12.4 12.5 12.6
12.3.2CreateNewStories………………………….. 139 12.3.3Store&UpdateUnit …………………………. 144 JavaScriptFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 SourceCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 12.6.1 Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 12.6.2APIEndpoints ……………………………. 152 12.6.3YourCode ………………………………152
13. Pagination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 13.1 Implementation ……………………………… 155
13.2 13.3
PaginationLinks……………………………… 158 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
14.1 14.2
14.3 14.4 14.5 14.6 14.7
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 14.1.1Compatibility…………………………….. 164 VariableDeclarations …………………………… 164 14.2.1LetDeclarations …………………………… 164 14.2.2 Constant Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 ArrowFunctions……………………………… 165 Modules………………………………….166 Classes…………………………………..167 DefaultParameterValues…………………………. 168 Templateliterals……………………………… 169
Building Large-Scale Applications . . . . . . . . . . . . 162
III
14. ECMAScript 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
15. AdvancedWorkflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
15.1
15.2
15.3
CompilingES6withBabel ………………………… 171 15.1.1Installation ……………………………… 173 15.1.2Configuration ……………………………. 175 15.1.3Buildalias ……………………………… 176 15.1.4 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 15.1.5Homework ……………………………… 178
WorkflowAutomationwithGulp …………………….. 180 15.2.1TaskRunners…………………………….. 180 15.2.2Installation ……………………………… 181 15.2.3 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 15.2.4 Watch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 15.2.5Homework ……………………………… 183
ModuleBundlingwithWebpack . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 15.3.1ModuleBundlers…………………………… 184
CONTENTS
15.3.2 Webpack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 15.3.3Installation ……………………………… 188 15.3.4 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 15.3.5Automation……………………………… 189
15.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 16. Working with Single File Components . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
16.1
16.2
16.3
Thevue-cli . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 16.1.1Vue’sTemplates …………………………… 193 16.1.2Installation ……………………………… 194 16.1.3 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
WebpackTemplate ……………………………. 197 16.2.1 Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 16.2.2index.html ……………………………… 200 16.2.3 Hello.vue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 16.2.4 App.vue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 16.2.5 main.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Forming.vueFiles ……………………………. 205 16.3.1NestedComponents …………………………. 214
17. Eliminating Duplicate State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
17.1 SharingwithProperties………………………….. 219
17.2 GlobalStore ……………………………….. 224
18. Swapping Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 18.1 DynamicComponents ………………………….. 228 18.1.1Theisspecialattribute ……………………….. 228 18.1.2Navigation ……………………………… 231
19. Vue Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
19.1 Installation…………………………………236
19.2 Usage……………………………………237
19.3 NamedRoutes……………………………….239
19.4 Historymode ………………………………. 240
19.5 Nestedroutes ………………………………. 242
19.6 Auto-CSSactiveclass……………………………244
19.6.1CustomActiveClass…………………………. 246
19.7 RouteObject………………………………..247
19.8 DynamicSegments ……………………………. 248
19.9 RouteAlias…………………………………255
19.10 ProgrammaticNavigation…………………………. 257
19.11 Transitions………………………………… 258
19.11.1Introduction …………………………….. 258 19.11.2Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
CONTENTS
19.11.33rd-partyCSSanimations ………………………. 261 19.12 NavigationGuards ……………………………. 262 19.13 Homework…………………………………264
Introduction
About Vue.js Vue.js Overview
Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is very easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.1
If you are an experienced frontend developer and you want to know how Vue.js compares to other libraries/frameworks, check out the Comparison with Other Frameworks chapter.
If you are interested to learn more information about Vue.js’ core take a look at Vue.js official guide2. What people say about Vue.js
“Vue.js is what made me love JavaScript. It’s extremely easy and enjoyable to use. It has a great ecosystem of plugins and tools that extend its basic services. You can quickly include it in any project, small or big, write a few lines of code and you are set. Vue.js is fast, lightweight and is the future of Front end development!”
—Alex Kyriakidis
“When I started picking up Javascript I got excited learning a ton of possibilities, but when my friend suggested to learn Vue.js and I followed his advice, things went wild. While reading and watching tutorials I kept thinking all the stuff I’ve done so far and how much easier it would be if I had invest time to learn Vue earlier. My opinion is that if you want to do your work fast, nice and easy Vue is the JS Framework you need. “
—Kostas Maniatis
1https://github.com/vuejs/awesome- vue#libraries- – plugins 2http://vuejs.org/guide/overview.html

About Vue.js iii
“Mark my words: Vue.js will sky-rocket in popularity in 2016. It’s that good.”
— Jeffrey Way
“Vue is what I always wanted in a JavaScript framework. It’s a framework that scales with you as a developer. You can sprinkle it onto one page, or build an advanced single page application with Vuex and Vue Router. It’s truly the most polished JavaScript framework I’ve ever seen.”
— Taylor Otwell
“Vue.js is the first framework I’ve found that feels just as natural to use in a server-rendered app as it does in a full-blown SPA. Whether I just need a small widget on a single page or I’m building a complex Javascript client, it never feels like not enough or like overkill.”
— Adam Wathan
“Vue.js has been able to make a framework that is both simple to use and easy to understand. It’s a breath of fresh air in a world where others are fighting to see who can make the most complex framework.”
— Eric Barnes
“The reason I like Vue.js is because I’m a hybrid designer/developer. I’ve looked at React, Angular and a few others but the learning curve and terminology has always put me off. Vue.js is the first JS framework I understand. Also, not only is it easy to pick up for the less confidence JS’ers, such as myself, but I’ve noticed experienced Angular and React developers take note, and liking, Vue.js. This is pretty unprecedented in JS world and it’s that reason I started London Vue.js Meetup.”
—Jack Barham

About Vue.js iv
Comparison with Other Frameworks Angular 1
Some of Vue’s syntax will look very similar to Angular (e.g. v-if vs ng-if). This is because there were a lot of things that Angular got right and these were an inspiration for Vue very early in its development. There are also many pains that come with Angular however, where Vue has attempted to offer a significant improvement.
Complexity
Vue is much simpler than Angular 1, both in terms of API and design. Learning enough to build non-trivial applications typically takes less than a day, which is not true for Angular 1.
Flexibility and Modularity
Angular 1 has strong opinions about how your applications should be structured, while Vue is a more flexible, modular solution. That’s why a Webpack template3 is provided, that can set you up within minutes, while also granting you access to advanced features such as hot module reloading, linting, CSS extraction, and much more.
Data binding
Angular 1 uses two-way binding between scopes, while Vue enforces a one-way data flow between components. This makes the flow of data easier to reason about in non-trivial applications.
Directives vs Components
Vue has a clearer separation between directives and components. Directives are meant to encapsulate DOM manipulations only, while components are self-contained units that have their own view and data logic. In Angular, there’s a lot of confusion between the two.
Performance
Vue has better performance and is much, much easier to optimize because it doesn’t use dirty checking. Angular 1 becomes slow when there are a lot of watchers, because every time anything in the scope changes, all these watchers need to be re-evaluated again. Also, the digest cycle may have to run multiple times to “stabilize” if some watcher triggers another update. Angular users often have to resort to esoteric techniques to get around the digest cycle, and in some situations, there’s simply no way to optimize a scope with many watchers.
3https://github.com/vuejs- templates/webpack

About Vue.js v
Vue doesn’t suffer from this at all because it uses a transparent dependency-tracking observation system with async queueing – all changes trigger independently unless they have explicit depen- dency relationships.
Interestingly, there are quite a few similarities in how Angular 2 and Vue are addressing these Angular 1 issues.
Angular 2
There is a separate section for Angular 2 because it really is a completely new framework. For example, it features a first-class component system, many implementation details have been completely rewritten, and the API has also changed quite drastically.
Size and Performance
In terms of performance, both frameworks are exceptionally fast and there isn’t enough data from real world use cases to make a verdict. However if you are determined to see some numbers, Vue 2.0 seems to be ahead of Angular 2 according to this 3rd party benchmark4.
Size wise, although Angular 2 with offline compilation and tree-shaking is able to get its size down considerably, a full-featured Vue 2.0 with compiler included (23kb) is still lighter than a tree-shaken bare-bone example of Angular 2 (50kb).
Flexibility
Vue is much less opinionated than Angular 2, offering official support for a variety of build systems, with no restrictions on how you structure your application. Many developers enjoy this freedom, while some prefer having only one Right Way to build any application.
Learning Curve
To get started with Vue, all you need is familiarity with HTML and ES5 JavaScript (i.e. plain JavaScript). With these basic skills, you can start building non-trivial applications within less than a day of reading the guide.
Angular 2’s learning curve is much steeper. Even without TypeScript, their Quickstart guide5 starts out with an app that uses ES2015 JavaScript, NPM with 18 dependencies, 4 files, and over 3,000 words to explain it all – just to say Hello World.
4http://stefankrause.net/js- frameworks- benchmark4/webdriver- ts/table.html 5https://angular.io/docs/js/latest/quickstart.html

About Vue.js vi
React
React and Vue share many similarities. They both:
• utilize a virtual DOM
• provide reactive and composable view components
• maintainfocusinthecorelibrary,withconcernssuchasroutingandglobalstatemanagement
handled by companion libraries
Performance Profiles
In every real-world scenario that has been tested so far, Vue outperforms React by a fair margin.
Render Performance
When rendering UI, manipulating the DOM is typically the most expensive operation and unfortu- nately, no library can make those raw operations faster. The best it can be done is:
1. Minimize the number of necessary DOM mutations. Both React and Vue use virtual DOM abstractions to accomplish this and both implementations work about equally well.
2. Add as little overhead as possible on top of those DOM manipulations. This is an area where Vue and React differ. In React, let’s say the additional overhead of rendering an element is 1 and the overhead of an average component is 2. In Vue, the overhead of an element would be more like 0.1, but the overhead of an average component would be 4, due to the setup required for the reactivity system.
This means that in typical applications, where there are many more elements than components being rendered, Vue will outperform React by a significant margin. In extreme cases however, such as using 1 normal component to render each element, Vue will usually be slower.
Both Vue and React also offer functional components, which are stateless and instanceless – and therefore, require less overhead. When these are used in performance-critical situations, Vue is once again faster.
Update Performance
In React, you need to implement shouldComponentUpdate everywhere and use immutable data structures to achieve fully optimized re-renders. In Vue, a component’s dependencies are automat- ically tracked so that it only updates when one of those dependencies change. The only further optimization that sometimes can be helpful in Vue is adding a key attribute to items in long lists.
This means updates in unoptimized Vue will be much faster than unoptimized React and actually, due to the improved render performance in Vue, even fully-optimized React will usually be slower than Vue is out-of-the-box.
In Development
About Vue.js vii
Obviously, performance in production is the most important and that’s what we’ve been discussing so far. Performance in development still matters though. The good news is that both Vue and React remain fast enough in development for most normal applications.
However, if you’re prototyping any high-performance data visualizations or animations, you may find it useful to know that in scenarios where Vue can’t handle more than 10 frames per second in development, we’ve seen React slow down to about 1 frame per second.
This is due to React’s many heavy invariant checks, which help it to provide many excellent warnings and error messages.
About Vue.js viii
Ember
Ember is a full-featured framework that is designed to be highly opinionated. It provides a lot of established conventions and once you are familiar enough with them, it can make you very productive. However, it also means the learning curve is high and flexibility suffers. It’s a trade-off when you try to pick between an opinionated framework and a library with a loosely coupled set of tools that work together. The latter gives you more freedom but also requires you to make more architectural decisions.
That said, it would probably make a better comparison between Vue core and Ember’s templating and object model layers:
• VueprovidesunobtrusivereactivityonplainJavaScriptobjectsandfullyautomaticcomputed properties. In Ember, you need to wrap everything in Ember Objects and manually declare dependencies for computed properties.
• Vue’s template syntax harnesses the full power of JavaScript expressions, while Handlebars’ expression and helper syntax is intentionally quite limited in comparison.
• Performance-wise, Vue outperforms Ember by a fair margin, even after the latest Glimmer engine update in Ember 2.0. Vue automatically batches updates, while in Ember you need to manually manage run loops in performance-critical situations.
About Vue.js ix
Polymer
Polymer is yet another Google-sponsored project and in fact was a source of inspiration for Vue as well. Vue’s components can be loosely compared to Polymer’s custom elements and both provide a very similar development style. The biggest difference is that Polymer is built upon the latest Web Components features and requires non-trivial polyfills to work (with degraded performance) in browsers that don’t support those features natively. In contrast, Vue works without any dependencies or polyfills down to IE9.
In Polymer 1.0, the team has also made its data-binding system very limited in order to compensate for the performance. For example, the only expressions supported in Polymer templates are boolean negation and single method calls. Its computed property implementation is also not very flexible.
Polymer custom elements are authored in HTML files, which limits you to plain JavaScript/CSS (and language features supported by today’s browsers). In comparison, Vue’s single file components allows you to easily use ES2015+ and any CSS preprocessors you want.
When deploying to production, Polymer recommends loading everything on-the-fly with HTML Imports, which assumes browsers implementing the spec, and HTTP/2 support on both server and client. This may or may not be feasible depending on your target audience and deployment environment. In cases where this is not desirable, you will have to use a special tool called Vulcanizer to bundle your Polymer elements. On this front, Vue can combine its async component feature with Webpack’s code-splitting feature to easily split out parts of the application bundle to be lazy-loaded. This ensures compatibility with older browsers while retaining great app loading performance.
About Vue.js x
Riot
Riot 2.0 provides a similar component-based development model (which is called a “tag” in Riot), with a minimal and beautifully designed API. Riot and Vue probably share a lot in design philosophies. However, despite being a bit heavier than Riot, Vue does offer some significant advantages:
• True conditional rendering. Riot renders all if branches and simply shows/hides them.
• A far more powerful router. Riot’s routing API is extremely minimal.
• More mature tooling support. Vue provides official support for Webpack, Browserify, and
SystemJS, while Riot relies on community support for build system integration.
• Transition effect system. Riot has none.
• Betterperformance.DespiteadvertisinguseofavirtualDOM,Riotinfactusesdirtychecking
and thus suffers from the same performance issues as Angular 1.
For updated comparisons feel free to check Vue.js guide.
Welcome About the Book
This book will guide you through the path of the rapidly spreading Javascript Framework called Vue.js!
Some time ago, we started a new project based on Laravel and Vue.js. After thoroughly reading Vue.js guide and a few tutorials, we discovered lack of resources about Vue.js around the web. During the development of our project, we gained a lot of experience, so we came up with the idea to write this book in order to share our acquired knowledge with the world. Now that Vue.js 2 is out we decided it was time to update our book by publishing a second version where all examples and their relative contents are rewritten.
This book is written in an informal, intuitive, and easy-to-follow format, wherein all examples are appropriately detailed enough to provide adequate guidance to everyone.
We’ll start from the very basics and through many examples we’ll cover the most significant features of Vue.js. By the end of this book, you will be able to create fast front end applications and increase the performance of your existing projects with Vue.js 2 integration.
Who is this Book for
Everyone who has spent time to learn modern web development has seen Bootstrap, Javascript, and many Javascript frameworks. This book is for anyone interested in learning a lightweight and simple Javascript framework. No excessive knowledge is required, though it would be good to be familiar with HTML and Javascript. If you dont’t know what the difference is between a string and an object, maybe you need to do some digging first.
This book is useful for developers who are new to Vue.js, as well as those who already use Vue.js and want to expand their knowledge. It is also helpful for developers who are looking to migrate to Vue.js 2.
Get In Touch
In case you would like to contact us about the book, send us feedback, or other matters you would like to bring to our attention, don’t hesitate to contact us.
Welcome
xii
Name
The Majesty of Vue.js Alex Kyriakidis Kostas Maniatis
Homework
Email Twitter
hello@tmvuejs.com @tmvuejs alex@tmvuejs.com @hootlex kostas@tmvuejs.com @kostaskafcas
The best way to learn code is to write code, so we have prepared one exercise at the end of most chapters for you to solve and actually test yourself on what you have learned. We strongly recommend you to try as much as possible to solve them and through them gain a better understanding of Vue.js. Don’t be afraid to test your ideas, a little effort goes a long way! Maybe a few different examples or ways will give you the right idea. Of course we are not merciless, hints and potential solutions will be provided!
You may begin your journey!
Sample Code
You can find most of the code examples used in the book on GitHub. You can browse around the code here6.
If you prefer to download it, you will find a .zip file here7.
This will save you from copying and pasting things out of the book, which would probably be
terrible.
Errata
Although every care have been taken to ensure the accuracy of our content, mistakes do happen. If you find a mistake in the book we would be grateful if you could report it to us. By doing so, you can protect other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please submit an issue on our GitHub repository8.
Conventions
The following notational conventions are used throughout the book. A block of code is set as follows:
JavaScript
6https://github.com/hootlex/the- majesty- of- vuejs- 2 7https://github.com/hootlex/the- majesty- of- vuejs- 2/archive/master.zip 8https://github.com/hootlex/the- majesty- of- vuejs- 2

Welcome xiii
1 function(x, y){
2 // this is a comment 3}
Code words in text, data are shown as follows: “Use .container for a responsive fixed width container.”
New terms and important words are shown in bold. Tips, notes, and warnings are shown as follows:
This is a Warning
This element indicates a warning or caution.
This is a Tip
This element signifies a tip or suggestion.
This is an Information box
Some special information here.
This is a Note
A note about the subject.
This is a Hint
A hint about the subject.
This is a Terminal Command
Commands to run in terminal.
This is a Comparison text
A small text comparing things relative to the subject.

Welcome
xiv
This is a link to Github.
Links lead to the repository of this book, where you can find the code samples and potential homework solutions of each chapter.

I Vue.js Fundamentals
1. Install Vue.js
When it comes to download Vue.js you have a few options to choose from.
1.1 Standalone Version 1.1.1 Download from vuejs.org
To install Vue you can simply download and include it with a script tag. Vue will be registered as a global variable.
You can download two versions of Vue.js:
1. Development Version from http://vuejs.org/js/vue.js1
2. Production Version from http://vuejs.org/js/vue.min.js2.
Tip: Don’t use the minified version during development. You will miss out all the nice
warnings for common mistakes.
1.1.2 Include from CDN
Vue.js.org3 recommends unpkg4, which will reflect the latest version as soon as it is published to npm.
You can find Vue.js also on jsdelivr5 or cdnjs6
It takes some time to sync with the latest version so you have to check frequently for
updates.
1http://vuejs.org/js/vue.js
2http://vuejs.org/js/vue.min.js 3https://vuejs.org/v2/guide/installation.html#CDN 4https://unpkg.com/vue/dist/vue.js 5https://cdn.jsdelivr.net/vue/2.0.1/vue.min.js 6https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js

Install Vue.js 3
1.2 Download using NPM
NPM is the recommended installation method when building large scale apps with Vue.js. It pairs nicely with a CommonJS module bundler such as Webpack7 or Browserify8.
1 # latest stable
2 $ npm install vue
3 # latest stable + CSP-compliant
4 $ npm install vue@csp
5 # dev build (directly from GitHub):
6 $ npm install vuejs/vue#dev
1.3 Download using Bower
1 # latest stable
2 $ bower install vue
For more installation instructions and updates take a loot at the Vue.js Installation Guide9
In most book examples we are including Vue.js from the cdn, although you are free to install it using any method you like.
7http://webpack.github.io/ 8http://browserify.org/ 9http://vuejs.org/guide/installation.html

1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
2. Getting Started
Let’s start with a quick tour of Vue’s data binding features. We’re going to make a simple application that will allow us to enter a message and have it displayed on the page in real time. It’s going to demonstrate the power of Vue’s two-way data binding. In order to create our Vue application, we need to do a little bit of setting up, which just involves creating an HTML page.
In the process you will get the idea of the amount of time and effort we save using a javascript Framework like Vue.js instead of a javascript tool (library) like jQuery.
2.1 Hello World
We will create a new file and we will drop some boilerplate code in. You can name it anything you like, this one is called hello.html.

Hello Vue

Greetings your Majesty!


This is a simple HTML file with a greeting message.
Now we will carry on and do the same job using Vue.js. First of all we will include Vue.js and create a new Instance.

Hello Vue

Greetings your majesty!


10
11
12
13
14
15
16
17


For starters, we have included Vue.js from cdnjs1 and inside a script tag we have our Vue instance. We use a div with an id of #app which is the element we refer to, so Vue knows where to ‘look’. Try to think of this as a container that Vue works at. Vue won’t recognize anything outside of the targeted element. Use the el option to target the element you want.
Now we will assign the message we want to display, to a variable inside an object named data. Then we’ll pass the data object as an option to Vue constructor.
vardata={
message: 'Greetings your majesty!'
};
new Vue({
el: '#app',
data: data })
To display our message on the page, we just need to wrap the message in double curly brackets . So whatever is inside our message it will appear automatically in the h1 tag.

{{ message }}

It is as simple as that. Another way to define the message variable is to do it directly inside Vue
constructor in data object.
1https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js
1 2 3 4 5 6 7
1 2 3
Getting Started 5

6
data: {
message: 'Greetings your Majesty!'
Both ways have the exact same result, so you are again free to pick whatever syntax you like.
Info
The double curly brackets are not HTML but scripting code, anything inside mustache tags is called binding expression. Javascript will evaluate these expressions. The {{ message }} brings up the value of the Javascript variable. This piece of code {{1+2}} will display the number 3.
2.2 Two-way Binding
What is cool about Vue is that it makes our lives easier. Assume we want to change the message on user input, how can we easily accomplish it? In the example below we use v-model, a directive of Vue (we will cover more on directives in the next chapter). Then we use two-way data binding to dynamically change the message value when the user changes the message text inside an input. Data is synced on every input event by default.

{{ message }}

Getting Started 6
1
2
3
4 5}
new Vue({
el: '#app',
});
1 2 3 4
1
2
3
4 5} 6 })
new Vue({
el: '#app',
data: {
message: 'Greetings your Majesty!'
That’s it. Now our heading message and user input are bound! By using v-model inside the input tag we tell Vue which variable should bind with that input, in this case message .
Getting Started
7
Two-way data binding
Two-way data binding means that if you change the value of a model in your view, everything will be kept up to date.
2.3 Comparison with jQuery.
Probably, all of you have some experience with jQuery. If you don’t, it’s okay, the use of jQuery in this book is minimal. When we use it, its only to demonstrate how things can be done with Vue instead of jQuery and we will make sure everybody gets it.
Anyway, in order to better understand how data-binding is helping us to build apps, take a moment and think how you could do the previous example using jQuery. You would probably create an input element and give it an id or a class, so you could target it and modify it accordingly. After this, you would call a function that changes the desired element to match the input value, whenever the keyup event happens. It’s a real bother.
More or less, your snippet of code would look like this.
1 2 3 4 5 6 7 8 9
10
11
12
13
14
15
16
17
18

Hello Vue

Greetings your Majesty!




This is a simple example of comparison and, as you can see, Vue appears to be much more beautiful, less time consuming, and easier to grasp. Of course, jQuery is a powerful JavaScript library for Document Object Model (DOM) manipulation, but everything comes with its ups and downs!
Code Examples
You can find the code examples of this chapter on GitHub2.
Getting Started 8
2https://github.com/hootlex/the- majesty- of- vuejs- 2/blob/master/codes/chapter2.html
Getting Started 9
2.4 Homework
A nice and super simple introductory exercise is to create an HTML file with a Hello, {{name}} heading. Add an input and bind it to name variable. As you can imagine, the heading must change instantly whenever the user types or changes his name. Good luck and have fun!
Example Output
Note
The example’s output makes use of Bootstrap. If you are not familiar with bootstrap you can ignore it for now, it is covered in a later chapter.
Potential Solution
You can find a potential solution to this exercise here3. 3https://github.com/hootlex/the- majesty- of- vuejs- 2/blob/master/homework/chapter2.html

1 2 3 4 5 6 7 8 9
10 11 12 13 14
3. A Flavor of Directives.
In this chapter we are going through some basic examples of Vue’s directives. Well, if you have not used any Framework like Vue.js or Angular.js before, you probably don’t know what a directive is. Essentially, a directive is a special token in the markup that tells the library to do something to a DOM element. In Vue.js, the concept of directive is drastically simpler than that in Angular. Some of the directives are:
• v-show which is used to conditionally display an element
• v-if which can be used instead of v-show
• v-else which displays an element when v-if evaluates to false.
Also, there is v-for, which requires a special syntax and its use is for rendering (e.g. render a list of items based on an array). We will elaborate about the use of each, later in this book.
Let us begin and take a look at the directives we mentioned.
3.1 v-show
To demonstrate the first directive, we are going to build something simple. We will give you some tips that will make your understanding and work much easier! Suppose you find yourself in need to toggle the display of an element, based upon some set of criteria. Maybe a submit button shouldn’t display unless you’ve first typed in a message. How can we accomplish that with Vue?

Hello Vue




Here we have an HTML file with our known div id="app" and a textarea. Inside the textarea we are going to display our message. Of course, it is not yet bound and by this point you may have already figured it out. Also you may have noticed that in this example we are no longer using the minified version of Vue.js. As we have mentioned before, the minified version shouldn’t be used during development because you will miss out warnings for common mistakes. From now on, we are going to use this version in the book but of course you are free to do as you like.

Hello Vue

{{ $data }} 




It is time to bind the value of textarea with our message variable using v-model so it displays our message. Anything we type in is going to change in real time, just as we saw in the example from the previous chapter, where we were using an input. Additionally, here we are using a pre tag to spit out the data. What this is going to do, is to take the data from our Vue instance, filter it through json, and finally display the data in our browser. Vue will nicely format the output for us automatically whether it’s a string, number, array, or a plain object. We believe, that this gives a much better way
A Flavor of Directives. 12
to build and manipulate our data, since having everything right in front of you is better than looking constantly at your console.
Info
JSON (JavaScript Object Notation) is a lightweight data-interchange format. You can find more info on JSON here1. The output of {{ $data }} is bound with Vue data and will get updated on every change.
1
2
3 Hello Vue
4
5
6

7

You must send a message for help!

8
9
12

13 {{ $data }}
14 

15

16
17
18
26

A Flavor of Directives. 13
Info
An element with v-show will always be rendered and remain in the DOM. v-show simply toggles the display CSS property of the element.
1

You must send a message for help!

2
3
What we want to accomplish in this example, is to toggle different elements. In this step, we need to hide the warning inside the h1 tag, if a message is present. Οtherwise hide the message by setting its style to display: none.
3.2 v-if
At this point you might ask ‘What about the v-if directive we mentioned earlier?’. So, we will build the previous example again, only this time we’ll use v-if!
1
2
3 Hello Vue
4
5
6

7

You must send a message for help!

8
9
12

13 {{ $data }}
14 

15

16
17
18
As shown, the replacement of v-show with v-if works just as good as we thought. Go ahead and try to make your own experiments to see how this works! The only difference is that an element with v-if will not remain in the DOM.
3.2.1 Template v-if
If sometime we find ourselves in a position where we want to toggle the existence of multiple elements at once, we can use v-if on a