41,99 €
A project-based, practical guide to get hands-on into Vue.js 2.5 development by building beautiful, functional and performant web applications
If you are a web developer who now wants to create rich and interactive professional applications using Vue.js, then this book is for you. Prior knowledge of JavaScript is assumed. Familiarity with HTML, Node.js, and tools such as npm and webpack will be helpful but not necessary.
Do you want to make your web application amazingly responsive? Are you unhappy with your app's performance and looking forward to trying out ways to make your app more powerful? Then Vue.js, a framework for building user interfaces, is a great choice, and this book is the ideal way to put it through its paces.
This book's project-based approach will get you to build six stunning applications from scratch and gain valuable insights in Vue.js 2.5. You'll start by learning the basics of Vue.js and create your first web app using directives along with rich and attractive user experiences. You will learn about animations and interactivity by creating a browser-based game. Using the available tools and preprocessor, you will learn how to create multi-page apps with plugins. You will create highly efficient and performant functional components for your app. Next, you will create your own online store and optimize it. Finally, you will integrate Vue.js with the real-time Meteor library and create a dashboard showing real-time data.
By the end of this book you will have enough skills and will have worked through enough examples of real Vue.js projects to create interactive professional web applications with Vue.js 2.5.
Project-based guide that will help you start building applications immediately with an easy to follow approach. Our book will have 6 concrete projects. It will take readers through clear and logical steps, with screenshots and tips along the way to help you follow the guide and learn how to get more from Vue.js.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 333
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: November 2017
Production reference: 2081217
ISBN 978-1-78712-746-3
www.packtpub.com
Author
Guillaume Chau
Copy Editor
Dhanya Baburaj
Reviewer
Eduardo San Martin Morote
Project Coordinator
Sheejal Shah
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Shweta Pant
Indexer
Tejal Daruwale Soni
Content Development Editor
Arun Nadar
Graphics
Jason Monteiro
Technical Editor
Diksha Wakode
Production Coordinator
Shantanu Zagade
Guillaume Chau is the creator of integrations with Meteor (vue-meteor) and Apollo GraphQL (vue-apollo) to help developers build highly interactive, real-time, Vue-powered apps. He also created the official vue-curated app , which helps you to discover great packages, and he contributes to the ecosystem with tools such as vue-virtual-scroller and vue-supply. He built a customer portal app for a big energy company with large datasets and performance challenges and is now working with an innovative French start-up (WebRTC and real-time data).
Eduardo San Martin Morote is a frontend developer who loves open source. He has been contributing to open source since he started crafting applications. He mostly maintains Vue.js-related projects as Vue itself, vuefire, and vue-router. When he develops applications, he likes to focus on UX, and always works in a pragmatic way. He tends to reduce waste as much as possible by applying the lean methodology wherever he can. He also trains people in web development, and is patient and adapts his teaching to different levels.
For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at www.amazon.in/dp/178712746X.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Getting Started with Vue
Why another frontend framework?
A trending project
Compatibility requirements
One-minute setup
Creating an app
Vue devtools
Templates make your DOM dynamic
Displaying text
Adding basic interactivity with directives
Summary
Project 1 - Markdown Notebook
A basic note editor
Setting up the project
The note editor
The preview pane
Computed property
Text interpolation escaping
Displaying HTML
Saving the note
Watching changes
Using a method
Accessing the Vue instance
Loading the saved note
Lifecycle hooks
Initializing directly in the data
Multiple notes
The note list
A method to create a new note
Button and click events with v-on
Binding attributes with v-bind
Displaying a list with v-for
Selecting a note
The current note
Dynamic CSS classes
Conditional templates with v-if
Saving the notes with the deep option
Saving the selection
The note toolbar with extras inside
Renaming the note
Deleting the note
Favorite notes
The status bar
Created date with a filter
Text stats
Summary
Project 2 - Castle Duel Browser Game
Rules of the game
Setting up the project
The calm before the storm
The template option
The app state
The almighty components
Building the user interface
Our first component - the top bar
Adding some gameplay data to the state
Defining and using the components
Parent-to-child communication with Props
Props in our template
Displaying a card
Listening to native events on components
Child-to-parent communication with custom events
The hand
Animating the hand with transitions
A prettier animation
Playing a card
Animating the card list
The key special attribute
The CSS transitions
The overlays
Content distribution with slots
The 'player turn' overlay
The 'last play' overlay
The 'game over' overlay
Dynamic component
The overlay animation
Key attribute
The overlay background
Game world and scenery
The castles
Castle banners
Food and health bubbles
Banner bars
Animating a value
The animated clouds
The animation
Gameplay
Drawing cards
The initial hand
The hand
Playing a card
No cheating allowed
Removing the card from the hand
Waiting for the card transition to end
Applying the card effect
The next turn
New turn
Overlay close actions
Game Over!
Summary
Advanced Project Setup
Setting up our development environment
Installing vue-cli, the official command-line tool
Code editors
Our first full-blown Vue application
Scaffolding the project
Creating the app
Running our application
Render functions
Configuring babel
Babel Vue preset
Polyfills
Updating the dependencies
Updating manually
Updating automatically
Updating Vue
Building for production
Single-File Components
Template
Using Pug
Script
JSX
Style
Scoped styles
Adding preprocessors
Sass
Less
Stylus
Components inside components
Summary
Project 3 - Support Center
General app structure
Setting up the project
Routing and pages
Vue plugins
Our first routes with vue–router
Layouts with router–view
Creating routes
The router object
Router modes
Creating a navigation menu
Router links
Active class
FAQ - Consuming an API
Server setup
Using fetch
Loading animation
Extending Vue with our own plugin
Creating a plugin
Plugin options
Fetch method
Reusing code with mixins
Fetching remote data
Loading management
Error management
Support tickets
User authentication
Storing the user in a centralized state
Another plugin
Login forms
Smart form
Form input component
Customizing v-model
Login component
Style children of scoped elements
Improving our fetch plugin
Sign up operation
Login operation
User menu
Logout method
Private routes with navigation guards
Route meta properties
Router navigation guards
Redirecting to the wanted route
Initializing user authentication
Guest routes
Displaying and adding tickets
Tickets list
Session expiration
Nested routes
Fixing our navigation guard
Sending a form
Form textarea
Binding attributes
User actions
Backup user input
Advanced routing features
Dynamic routes with parameters
Dynamic remote data
The dynamic route
Not found page
Transitions
Scrolling behavior
Summary
Project 4 - Geolocated Blog
Google Auth and state management
Project setup
Creating the app
Some routing
State management with Vuex
Why do I need this?
The Vuex Store
The state is the source of truth
Mutations update the state
Strict mode
Time-travel debugging
Getters compute and return data
Actions for store operations
Mapping helpers
User state
Setting up Google OAuth
Login button
User in the store
Adapting the router
Adapting the fetch plugin
Check the user session on start
The profile picture
Synchronizing the store and the router
Embedding Google Maps
Installation
Getting the API key
Installing the library
Adding a map
Connecting the BlogMap and the store
Vuex modules
Namespaced module
Accessing global elements
BlogMap module and component
Mutations
Actions
Mapping in the component
User position
Centering on the user
Blog posts and comments
Posts store module
Rendering functions and JSX
Writing the view in JavaScript with render functions
Dynamic templates
Data objects
Virtual DOM
What is JSX?
Blog content structure (in JSX!)
No content
Creating a post
Draft store actions
Blog Map changes
Click handler
Ghost marker
Post form
Making the request
Fetching posts
Store action
Fetch posts action
Action dispatching
Displaying markers
Login and logout
Logout
Login
Selecting a post
Post details
Store changes for post selection and sending
Post Content component
Location info and scoped slots
Scoped slots to pass data to the parent
Implementing of the component
Comments - functional components
Store changes for comments
Functional component
Summary
Project 5 - Online Shop and Scaling Up
Advanced development workflow
Setting up the project
Generating a quick development API
Launching the app
Auto-prefixing CSS with PostCSS
Targeting specific browsers with browserslist
Improving code quality and style with ESLint
Configuring ESLint
Customizing the rules
Running ESLint
ESLint inside Webpack
Unit testing with Jest
Configuring Jest
Babel configuration for Jest
Our first unit test
ESLint and Jest globals
Jest snapshots
Updating the snapshots
Complementary topics
Internationalization and code-splitting
Code-splitting with dynamic imports
Automatically loading the user locale
Changing Language page
Server-side rendering
Universal App Structure
Client entry
Server entry
State management
Restoring the Vuex state on the client
Webpack configuration
Client configuration
Server configuration
Server-side setup
Page template
Express server
Creating and updating the renderer
Rendering the Vue app
Running our SSR app
Unnecessary fetch
Production build
Additional configuration
Extracting the style into CSS files
Production express server
New npm scripts
Summary
Project 6 - Real-time Dashboard with Meteor
Setting up the project
What is Meteor?
Installing Meteor
Creating the project
Our first Vue Meteor app
Routing
Production measures
Meteor collections integration
Setting up data
Adding a collection
Adding a Meteor method
Simulating measures
Inspecting the data
Dashboard and reporting
Progress bars library
Meteor publication
Creating the Dashboard component
Indicators
Listing the measures
Summary
Relatively new as a UI library, Vue is a very serious challenger to current leading libraries such as Angular and React. It has a lot to offer--it is simple, flexible, and very fast, yet it still provides all the features necessary to build a full-blown modern web app.
Its progressive nature makes it easy to get started with, and then you can use more advanced features to scale your app up. Vue also have a rich ecosystem surrounding it, including official first-party libraries for routing and state management, bootstrapping, and unit-testing. Vue even supports server-side rendering out of the box!
All this is possible thanks to an amazing community and an awesome core team that drive innovation on the web and make Vue a sustainable open source project.
To help you learn Vue and build apps with it, this book is structured as a series of six guides. Each guide is a concrete project, in which you will build a real application by yourself. This means you will have six Vue apps up and running by the end!
Just like Vue, the projects are progressive and introduce new topics step by step to make your learning experience easier. The first projects don't require extensive configuration or build tools, so you can make concrete apps right away. Then, more advanced topics will be progressively added to the project so that you will have a complete skill set by the end of the book.
Chapter 1, Getting Started with Vue,covers how to create a basic Vue app with a dynamic template and basic interactivity, thanks to directives.
Chapter 2, Project 1 - Markdown Notebook, explores the creation of a complete Vue app with features such as computed properties, methods, life cycle hooks, list displays, DOM events, dynamic CSS, template conditionals, and filter formatting.
Chapter 3, Project 2 - Castle Duel Browser Game, explains the creation of a browser card game structured as a tree of reusable components that communicate with each other. It also features animations and dynamic SVG graphics.
Chapter 4, Advanced Project Setup, focuses on how to use the official Vue command-line tool to bootstrap a full blown project with webpack, babel, and more build tools. It also covers the Single-File Component format, allowing readers to create components as building blocks.
Chapter 5, Project 3 - Support Center, takes you through how to structure a multipage app with the official routing library--nested routes, dynamic parameters, navigation guards, and such. The project also features a custom user login system.
Chapter 6, Project 4 - Geolocated Blog, walks through the creation of an app featuring Google OAuth login and the Google Maps API. This chapter also covers the important topic of state management using the official VueX library, plus fast functional components.
Chapter 7, Project 5 - Online Shop and Scaling up, outlines advanced development techniques such as checking code quality with ESLint, unit testing Vue components with Jest, translating an app into multiple languages, and improving speed and SEO with server-side rendering.
Chapter 8, Project 6 - Real-time Dashboard with Meteor, teaches you how to use Vue in a Meteor app in order to take advantage of the real-time capabilities of this full-stack framework.
To follow this book, you will only need a text or code editor (Visual Studio Code and Atom are recommended) and a web browser (preferably the latest version of Firefox or Chrome for the development tools).
If you are a web developer who now wants to create rich and interactive professional applications using Vue.js, then this book is for you. Prior knowledge of JavaScript is assumed. Familiarity with HTML, Node.js, and tools such as npm and webpack will be helpful, but not necessary.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "We can select HTML elements through the use of the d3.select function."
A block of code is set as follows:
class
Animal{
public
:
virtual
void
Speak(
void
)
const
//virtual in the base class
{ //Using the Mach 5 console print M5DEBUG_PRINT("...\n");}
New terms
and
important words
are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Clicking the
Next
button moves you to the next screen."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to [email protected], and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Vue-js-2-Web-Development-Projects. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!.
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file fromhttps://www.packtpub.com/sites/default/files/downloads/Vuejs2WebDevelopmentProjects_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Vue (https://vuejs.org/) is a JavaScript library focused on building web user interfaces. In this chapter, we will meet the library and after a brief introduction, we will start creating a web app, laying the ground for the different projects we will build together in this book.
Vue is a relative newcomer in the JavaScript frontend landscape, but a very serious challenger to the current leading libraries. It is simple, flexible, and very fast, while still providing a lot of features and optional tools that can help you build a modern web app efficiently. Its creator, Evan You, calls it the progressive framework:
Vue is incrementally adoptable, with a core library focused on user interfaces that you can use in existing projects
You can make small prototypes all the way up to large and sophisticated web applications
Vue is approachable--the beginners can pick up the library easily, and the confirmed developers can be productive very quickly
Vue roughly follows a Model-View-ViewModel architecture, which means the View (the user interface) and the Model (the data) are separated, with the ViewModel (Vue) being a mediator between the two. It handles the updates automatically and has been already optimized for you. Therefore, you don't have to specify when a part of the View should update because Vue will choose the right way and time to do so.
The library also takes inspiration from other similar libraries such as React, Angular, and Polymer. The following is an overview of its core features:
A reactive data system that can update your user interface automatically, with a lightweight virtual-DOM engine and minimal optimization efforts, is required
Flexible View declaration--artist-friendly HTML templates, JSX (HTML inside JavaScript), or hyperscript render functions (pure JavaScript)
Composable user interfaces with maintainable and reusable components
Official companion libraries that come with routing, state management, scaffolding, and more advanced features, making Vue a non-opinionated but fully fleshed out frontend framework
Evan You started working on the first prototype of Vue in 2013, while working at Google, using Angular. The initial goal was to have all the cool features of Angular, such as data binding and data-driven DOM, but without the extra concepts that make this framework opinionated and heavy to learn and use.
The first public release was published on February 2014 and had immediate success the very first day, with HackerNews frontpage, /r/javascript at the top spot and 10k unique visits on the official website.
The first major version 1.0 was reached in October 2015, and by the end of that year, the npm downloads rocketed to 382k ytd, the GitHub repository received 11k stars, the official website had 363k unique visitors, and the popular PHP framework Laravel had picked Vue as its official frontend library instead of React.
The second major version, 2.0, was released in September 2016, with a new virtual DOM-based renderer and many new features such as server-side rendering and performance improvements. This is the version we will use in this book. It is now one of the fastest frontend libraries, outperforming even React according to a comparison refined with the React team (https://vuejs.org/v2/guide/comparison). At the time of writing this book, Vue was the second most popular frontend library on GitHub with 72k stars, just behind React and ahead of Angular 1 (https://github.com/showcases/front-end-javascript-frameworks).
The next evolution of the library on the roadmap includes more integration with Vue-native libraries such as Weex and NativeScript to create native mobile apps with Vue, plus new features and improvements.
Today, Vue is used by many companies such as Microsoft, Adobe, Alibaba, Baidu, Xiaomi, Expedia, Nintendo, and GitLab.
Vue doesn't have any dependency and can be used in any ECMAScript 5 minimum-compliant browser. This means that it is not compatible with Internet Explorer 8 or less, because it needs relatively new JavaScript features such as Object.defineProperty, which can't be polyfilled on older browsers.
In this book, we are writing code in JavaScript version ES2015 (formerly ES6), so for the first few chapters, you will need a modern browser to run the examples (such as Edge, Firefox, or Chrome). At some point, we will introduce a compiler called Babel that will help us make our code compatible with older browsers.
Without further ado, let's start creating our first Vue app with a very quick setup. Vue is flexible enough to be included in any web page with a simple script tag. Let's create a very simple web page that includes the library, with a simple div element and another script tag:
<html><head> <meta charset="utf-8"> <title>Vue Project Guide setup</title></head><body> <!-- Include the library in the page --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <!-- Some HTML --> <div id="root"> <p>Is this an Hello world?</p> </div> <!-- Some JavaScript --> <script> console.log('Yes! We are using Vue version', Vue.version) </script></body></html>
In the browser console, we should have something like this:
Yes! We are using Vue version 2.0.3
As you can see in the preceding code, the library exposes a Vue object that contains all the features we need to use it. We are now ready to go.
With Vue, we have several systems at our disposal to write our View. For now, we will start with templates. A template is the easiest way to describe a View because it looks like HTML a lot, but with some extra syntax to make the DOM dynamically update very easily.
Let's add some interactivity to our otherwise quite static app, for example, a text input that will allow the user to change the message displayed. We can do that in templates with special HTML attributes called directives.
The directive we need here is v-model, which will bind the value of our <input> element with our message data property. Add a new <input> element with the v-model="message" attribute inside the template:
<div id="root"> <p>{{ message }}</p> <!-- New text input --> <input
v-model
="message" /></div>
Vue will now update the message property automatically when the input value changes. You can play with the content of the input to verify that the text updates as you type and the value in the devtools changes:
There are many more directives available in Vue, and you can even create your own. Don't worry, we will cover that in later chapters.
In this chapter, we quickly set up a web page to get started using Vue and wrote a simple app. We created a Vue instance to mount the Vue app on the page and wrote a template to make the DOM dynamic. Inside this template, we used a JavaScript expression to display text, thanks to text interpolations. Finally, we added some interactivity with an input element that we bound to our data with the v-model directive.
In the next chapter, we will create our first real web app with Vue--a markdown notebook. We will need more Vue superpowers to turn the development of this app into a fun and swift experience.
The first app we will create is a markdown notebook, using several Vue features in a step-by-step manner. We will reuse what we saw in Chapter 1, Getting Started with Vue, and add more elements on top of it, such as useful directives, events for user interaction, more instance options, and filters to process values.
Before we start writing the code, let's talk about the app and review our objectives:
The notebook app will allow the user to write notes in markdown
The markdown will be previewed in real time
The users will be able to add as many notes as they want
The notes will be restored the next time the user visits the app
To do that, we will divide the user interface into three sections:
A main section in the middle with the note editor
A right pane, which previews the markdown of the current node
A left pane, with the list of notes and a button to add a new one
Here is what it will look like at the end of the chapter:
We will start small with a very simple markdown note app that only displays a text editor on the left and a markdown preview on the right. Then, we will turn it into a full notebook with multiple note support.
For this project, we will have a few files ready to get us started:
First, download
simple-notebook
project files and extract them in the same folder. Open the
index.html
file and add a
div
element with the
notebook
ID and a nested
section
element with the
main
class. You should have the following content inside the file:
<html> <head> <title>Notebook</title> <!-- Icons & Stylesheets --> <link href="https://fonts.googleapis.com/icon? family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="style.css" /> </head> <body> <!-- Include the library in the page --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <!-- Notebook app --> <div id="notebook"> <!-- Main pane --> <section class="main"> </section> </div> <!-- Some JavaScript --> <script src="script.js"></script> </body> </html>
Now, open the
script.js
file to add some JavaScript. Just like you did in
Chapter 1
,
Getting Started with Vue
, create a Vue instance mounted on the
#notebook
element with a Vue constructor:
// New VueJS instance new
Vue
({ // CSS selector of the root DOM element
el
: '#notebook', })
Then, add a data property called
content
that will hold the content of your note:
new Vue({ el: '#notebook', // Some data
data
() { return { content: 'This is a note.', } }, })
Now you are ready to create your first real Vue app.
Now that we have our app running, let's add the text editor. We will use a simple textarea element and the v-model directive we saw in Chapter 1, Getting Started with Vue.
Create a section element and put the textarea inside, then add the v-model directive bound to our content property:
<!-- Main pane --> <section class="main"> <textarea v-model="content"></textarea> </section>
Now, if you change the text ;inside the note editor, the value of content should automatically chance in the devtools.
A very powerful feature of Vue is the computed property. It allows us to define new properties that combine any amount of properties and use transformations, such as converting a markdown string into HTML--that's why its value is defined by a function. A computed property has the following features:
The value is cached so that the function doesn't rerun if it's not necessary, preventing useless computation
It is automatically updated as needed when a property used inside the function has changed
A computed property can be used exactly like any property (and you can use computed properties inside other computed properties)
It is not computed until it is really used somewhere in the app
This will help us automatically convert the note markdown into valid HTML, so we can display a preview in real time. We just need to declare our computed property in the computed option:
// Computed properties
computed
: { notePreview () { // Markdown rendered to HTML return marked(this.content) }, },
Let's try to display our note in a new pane using a text interpolation:
Create an
<aside>
element with the
preview
class, which displays our
notePreview
computed property:
<!-- Preview pane --> <aside class="preview"> {{ notePreview }} </aside>
