Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Vue.js 2.x by Example
Vue.js 2.x by Example

Vue.js 2.x by Example: Example-driven guide to build web apps with Vue.js for beginners

By Mike Street
$43.99 $29.99
Book Dec 2017 412 pages 1st Edition
eBook
$43.99 $29.99
Print
$54.99
Subscription
$15.99 Monthly
eBook
$43.99 $29.99
Print
$54.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Dec 27, 2017
Length 412 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788293464
Category :
Table of content icon View table of contents Preview book icon Preview Book

Vue.js 2.x by Example

Getting Started with Vue.js

Vue (pronounced view) is a very powerful JavaScript library created for building interactive user interfaces. Despite having the ability to handle large single-page applications, Vue is also great for providing a framework for small, individual use cases. Its small file size means it can be integrated into existing ecosystems without adding too much bloat.

It was built to have a simple API, which makes it easier to get started in comparison with its rivals: React and Angular. Although it borrows some of the logic and methodologies from these libraries, it has identified a need for developers for a simpler library for building applications.

Unlike React or Angular, one of the benefits of Vue is the clean HTML output it produces. Other JavaScript libraries tend to leave the HTML scattered with extra attributes and classes in the code, whereas Vue removes these to produce clean, semantic output.

In the first part of this book, we are going to build an application that uses a JSON string to display data. We will then look at filtering and manipulating data, before moving on to building reusable components to reduce duplication in our code.

In this chapter, we will look at:

  • How to get started with Vue by including the JavaScript file
  • How to initialize your first Vue instance and look at the data object
  • Examining computed functions and properties
  • Learning about Vue methods

Creating the workspace

To use Vue, we first need to include the library in our HTML and initialize it. For the examples in the first section of this book, we are going to be building our application in a single HTML page. This means the JavaScript to initialize and control Vue will be placed at the bottom of our page. This will keep all our code contained, and means it will easily run on your computer. Open your favorite text editor and create a new HTML page. Use the following template as a starting point:

      <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue.js App</title>
</head>
<body>
<div id="app">
</div>
<script src="https://unpkg.com/vue"></script>
<script type="text/javascript">
// JS Code here
</script>
</body>
</html>

The main HTML tags and structure should be familiar to you. Let's run over a few of the other aspects.

Application space

This is the container for your application and provides a canvas for Vue to work in. All the Vue code will be placed within this tag. The actual tag can be any HTML element - main, section, and so on. The ID of the element needs to be unique, but again, can be anything you wish. This allows you to have multiple Vue instances on one page or identify which Vue instance relates to which Vue code:

      <div id="app">
</div>

During the tutorials, this element with the ID will be referred to as the app space or view. It should be noted that all HTML and tags and code for your application should be placed within this container.

Although you can use most HTML tags for your application space, you cannot initialize Vue on the <body> or <HTML> tags - if you do so, Vue will throw a JavaScript error and will fail to initialize. You will have to use an element inside your body.

Vue library

For the examples in this book, we are going to be using a hosted version of Vue.js from a CDN (Content Delivery Network) unpkg. This ensures that we have the latest version of Vue in our application, and also means we do not need to create and host other JavaScript files. Unpkg is an independent site that hosts popular libraries. It enables you to quickly and easily add a JavaScript package to your HTML, without having to download and host the file yourself:

      <script src="https://unpkg.com/vue"></script>

When deploying your code, it is a good practice to serve up your libraries from local files rather than relying on CDNs. This ensures that your implementation will work with the currently - saved version, should they release an update. It will also increase the speed of your application, as it will not need to request the file from another server.

The script block following the library include is where we are going to be writing all our JavaScript for our Vue application.

Initializing Vue and displaying the first message

Now that we have a template set up, we can initialize Vue and bind it to the HTML app space by using the following code:

      const app = new Vue().$mount('#app');

This code creates a new instance of Vue and mounts it on the HTML element with the ID of app. If you save your file and open it up in a browser, you will notice nothing has happened. However, under the hood, this one line of code has linked the div with the app variable, which is an instance of a Vue application.

Vue itself has many objects and properties that we can now use to build our app. The first one you will encounter is the el property. Using an HTML ID, this property tells Vue which element it should bind to and where the app is going to be contained. This is the most common way of mounting your Vue instance and all Vue code should happen within this element:

      const app = new Vue({
el: '#app'
});

When the el property isn't specified in the instance, Vue initializes in an unmounted state—this allows any functions or methods you may have specified to run before mounting, to run and complete. You can then independently call the mounting function when ready. Behind the scenes, when using the el property, Vue is mounting the instance using a $.mount function. If you do want to wait, the $mount function can be called separately, for example:

      const app = new Vue();

// When ready to mount app:
app.$mount('#app');

However, as we will not need to delay the execution of our mount timing throughout the book, we can use the el element with the Vue instance. Using the el property is also the most common way of mounting the Vue app.

Alongside the el value, Vue has a data object that contains any data we need to access the app or app space. Create a new data object within the Vue instance and assign a value to a property by doing the following:

      const app = new Vue({
el: '#app',

data: {
message: 'Hello!'
}
});

Within the app space, we now have access to the message variable. To display data within the app, Vue uses the Mustache templating language to output data or variables. This is achieved by placing the variable name between double curly brackets {{ variable }}. Logic statements, such as if or foreach, get HTML attributes, which will be covered later in the chapter.

Within the app space, add the code to output the string:

      <div id="app">
{{ message }}
</div>

Save the file, open it up in your browser, and you should be presented with your Hello! string.

If you don't see any output, check the JavaScript console to see if there are any errors. Ensure the remote JavaScript file is loading correctly, as some browsers and operating systems require additional security steps before allowing some remote files to be loaded when viewing pages locally on your computer.

The data object can handle multiple keys and data types. Add some more values to the data object and see what happens - make sure you add a comma after each value. Data values are simple JavaScript and can handle basic math, too - try adding a new price key and setting the value to 18 + 6 to see what happens. Alternatively, try adding a JavaScript array and printing it out:

      const app = new Vue({
el: '#app',

data: {
message: 'Hello!',
price: 18 + 6,
details: ['one', 'two', 'three']
}
});

In your app space, you can now output each of those values - {{ price }} and {{ details }} now output data - although the list may not be quite what you had expected. We'll cover using and displaying lists in Chapter 2, Displaying, Looping, Searching, and Filtering Data.

All the data in Vue is reactive and can be updated by either the user or the application. This can be tested by opening up the browser's JavaScript console and updating the content yourself. Try typing app.message = 'Goodbye!'; and pressing Enter - your app's content will update. This is because you are referencing the property directly - the first app refers to the const app variable that your app is initialized to in your JavaScript. The period denotes a property within there, and the message refers to the data key. You could also update app.details or price to anything you want!

Computed values

The data object in Vue is great for storing and retrieving data directly, however, there may be times where you want to manipulate the data before outputting it in your applications. We can do that using the computed object in Vue. Using this technique, we are able to start adhering to the MVVM (Model-View-ViewModel) methodology.

MVVM is a software architectural pattern where you separate out various parts of your application into distinct sections. The Model (or data) is your raw data input - be it from an API, database, or hardcoded data values. In the context of Vue, this is typically the data object we used earlier.

The view is the frontend of your application. This should just be used for outputting the data from the Model, and should not contain any logic or data manipulation, with the exception of some unavoidable if statements. For the Vue applications, this is all the code placed within the <div id="app"></div> tags.

The ViewModel is the bridge between the two. It allows you to manipulate the data from the Model before it is output by the view. Examples of this could range from changing a string to uppercase or prefixing a currency symbol, up to filtering out discounted products from a list or calculating the total value of a field across an array. In Vue, this is where the computed object comes in.

The computed object can have as many properties as required - however, they must be functions. These functions can utilize data already on the Vue instance and return a value, be it a string, number, or array that can then be used in the view.

The first step is to create a computed object within our Vue application. In this example, we are going to use a computed value to convert our string to lowercase, so set the value of message back to a string:

      const app = new Vue({
el: '#app',

data: {
message: 'Hello Vue!'
},
computed: {
}
});
Don't forget to add a comma (,) after the closing curly bracket (}) of your data object so Vue knows to expect a new object.

The next step is to create a function inside the computed object. One of the hardest parts of development is naming things - make sure the name of your function is descriptive. As our application is quite small and our manipulation basic, we'll name it messageToLower:

      const app = new Vue({
el: '#app',
data: {
message: 'HelLO Vue!'
},
computed: {
messageToLower() {
return 'hello vue!';
}
}
});

In the preceding example, I've set it to return a hardcoded string, which is a lowercased version of the contents of the message variable. Computed functions can be used exactly as you would use a data key in the view. Update the view to output {{ messageToLower }} instead of {{ message }} and view the result in your browser.

There are a few issues with this code, however. Firstly, if the value of messageToLower was being hardcoded, we could have just added it to another data property. Secondly, if the value of message changes, the lowercase version will now be incorrect.

Within the Vue instance, we are able to access both data values and computed values using the this variable - we'll update the function to use the existing message value:

      computed: {
messageToLower() {
return this.message.toLowerCase();
}
}

The messageToLower function now references the existing message variable and, using a native JavaScript function, converts the string to lower case. Try updating the message variable in your application, or in the JavaScript console, to see it update.

Computed functions are not just limited to basic functionality - remember, they are designed to remove all logic and manipulations from the view. A more complex example might be the following:

      const app = new Vue({
el: '#app',
data: {
price: 25,
currency: '$',
salesTax: 16
},
computed: {
cost() {
// Work out the price of the item including
salesTax
let itemCost = parseFloat(
Math.round((this.salesTax / 100) *
this.price) + this.price).toFixed(2);
// Add text before displaying the currency and
amount
let output = 'This item costs ' +
this.currency + itemCost;
// Append to the output variable the price
without salesTax
output += ' (' + this.currency + this.price +
' excluding salesTax)';
// Return the output value
return output;
}
}
});

Although this might seem advanced at first glance, the code is taking a fixed price and calculating what it would be with sales tax added. The price, salesTax, and currency symbol are all stored as values on the data object and accessed within the cost() computed function. The view outputs {{ cost }}, which produces the following:

This item costs $29.00 ($25 excluding sales tax)

Computed functions will recalculate and update if any data is updated, by either the user or the application itself. This allows for our function to dynamically update based on the price and salesTax values. Try one of the following commands in the console in your browser:

   app.salesTax = 20
   app.price = 99.99

The paragraph and prices will update instantly. This is because computed functions are reactive to the data object and the rest of the application.

Methods and reusable functions

Within your Vue application, you may wish to calculate or manipulate data in a consistent or repetitive way or run tasks that require no output to your view.For example, if you wanted to calculate the sales tax on every price or retrieve some data from an API before assigning it to some variables.

Rather than creating computed functions for each time, we need to do this, Vue allows you to create functions or methods. These get declared in your application and can be accessed from anywhere - similar to the data or computed functions.

Add a method object to your Vue application and note the updates to the data object:

      const app = new Vue({
el: '#app',

data: {
shirtPrice: 25,
hatPrice: 10,

currency: '$',
salesTax: 16
},
methods: {

}
});

Within the data object, the price key has been replaced with two prices - shirtPrice and hatPrice. We'll create a method to calculate the sales tax for each of these prices.

Similar to creating a function for the computed object, create a method function title called calculateSalesTax. This function needs to accept a single parameter, which will be the price. Inside, we will use the code from the previous example to calculate the sales tax. Remember to replace this.price with just the parameter name: price, as shown here:

      methods: {
        calculateSalesTax(price) {
          // Work out the price of the item including   
sales tax return parseFloat( Math.round((this.salesTax / 100) * price)
+ price).toFixed(2); }
}

Pressing save will not do anything to our application - we need to call the function. In your view, update the output to use the function and pass in the shirtPrice variable:

      <div id="app">
{{ calculateSalesTax(shirtPrice) }}
</div>

Save your documents and check the result in the browser - is it what you expected? The next task is to prepend the currency. We can do that by adding a second method that returns the parameter passed into the function with the currency at the beginning of the number:

      methods: {
calculateSalesTax(price) {
// Work out the price of the item including
sales tax
return parseFloat(
Math.round((this.salesTax / 100) * price) +
price).toFixed(2);
},
addCurrency(price) {
return this.currency + price;
}
}

In our view, we then update our output to utilize both methods. Rather than assigning to a variable, we can pass the first function, calculateSalesTax, as the parameter for the second addCurrency function. This works because of the first method, calculateSalesTax, accepts the shirtPrice parameter and returns the new amount. Instead of saving this as a variable and passing the variable into the addCurrency method, we pass the result directly into this function, which is the calculated amount:

      {{ addCurrency(calculateSalesTax(shirtPrice)) }}

However, it would start to get tiresome having to write these two functions every time we needed to output the price. From here, we have two options:

  • We can create a third method, titled cost() - which accepts the price parameter and passes the input through the two functions
  • Create a computed function, such as shirtCost, which uses this.shirtPrice instead of having a parameter passed in

We could, alternatively, create a method titled shirtCost that does the same as our computed function; however, it's better to practice to use computed in this case.

This is because computed functions are cached, whereas method functions are not. If you imagine our methods being a lot more complicated than they currently are, calling function after function repeatedly (for example, if we wanted to display the price in several locations) could have a performance impact. With computed functions, as long as the data does not change, you can call it as many times as you want, with the result being cached by the application. If the data does change, it only needs to recalculate once, and re-cache that result.

Make a computed function for both the shirtPrice and hatPrice, so that both variables can be used in the view. Don't forget that to call the functions internally you must use the this variable - for example, this.addCurrency(). Use the following HTML code as the template for your view:

      <div id="app">
<p>The shirt costs {{ shirtCost }}</p>
<p>The hat costs {{ hatCost }}</p>
</div>

Have a go at creating the computed functions yourself before comparing against the following code. Don't forget that there are many ways to do things in development, so don't worry if your code works but doesn't match the following example:

      const app = new Vue({
el: '#app',
data: { shirtPrice: 25, hatPrice: 10, currency: '$', salesTax: 16 }, computed: { shirtCost() { returnthis.addCurrency(this.calculateSalesTax(
this.shirtPrice)) }, hatCost() { return this.addCurrency(this.calculateSalesTax(
this.hatPrice)) }, }, methods: { calculateSalesTax(price) { // Work out the price of the item including
sales tax return parseFloat( Math.round((this.salesTax / 100) * price) +
price).toFixed(2); }, addCurrency(price) { return this.currency + price; } } });

The result, although basic, should look like the following:

Summary

In this chapter, we learned how to get started with the Vue JavaScript framework. We examined the data, computed, and methods objects within the Vue instance. We covered how to use each one within the framework and utilize each of its advantages.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • We bridge the gap between "learning" and "doing" by providing real-world examples that will improve your web development skills with Vue.js
  • Explore the exciting features of Vue.js 2 through practical and interesting examples
  • Explore modern development tools and learn how to utilize them by building applications with Vue.js

Description

Vue.js is a frontend web framework which makes it easy to do just about anything, from displaying data up to creating full-blown web apps, and has become a leading tool for web developers. This book puts Vue.js into a real-world context, guiding you through example projects that helps you build Vue.js applications from scratch. With this book, you will learn how to use Vue.js by creating three Single Page web applications. Throughout this book, we will cover the usage of Vue, for building web interfaces, Vuex, an official Vue plugin which makes caching and storing data easier, and Vue-router, a plugin for creating routes and URLs for your application. Starting with a JSON dataset, the first part of the book covers Vue objects and how to utilize each one. This will be covered by exploring different ways of displaying data from a JSON dataset. We will then move on to manipulating the data with filters and search and creating dynamic values. Next, you will see how easy it is to integrate remote data into an application by learning how to use the Dropbox API to display your Dropbox contents in an application In the final section, you will see how to build a product catalog and dynamic shopping cart using the Vue-router, giving you the building blocks of an e-commerce store.

What you will learn

Looping through data with Vue.js Searching and filtering data Using components to display data Getting a list of files using the dropbox API Navigating through a file tree and loading folders from a URL Caching with Vuex Pre-caching for faster navigation Introducing vue-router and loading components Using vue-router dynamic routes to load data Using vue-router and Vuex to create an ecommerce store

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Dec 27, 2017
Length 412 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788293464
Category :

Table of Contents

13 Chapters
Preface Chevron down icon Chevron up icon
Getting Started with Vue.js Chevron down icon Chevron up icon
Displaying, Looping, Searching, and Filtering Data Chevron down icon Chevron up icon
Optimizing your App and Using Components to Display Data Chevron down icon Chevron up icon
Getting a List of Files Using the Dropbox API Chevron down icon Chevron up icon
Navigating through the File Tree and Loading Folders from the URL Chevron down icon Chevron up icon
Caching the Current Folder Structure Using Vuex Chevron down icon Chevron up icon
Pre-Caching Other Folders and Files for Faster Navigation Chevron down icon Chevron up icon
Introducing Vue-Router and Loading URL-Based Components Chevron down icon Chevron up icon
Using Vue-Router Dynamic Routes to Load Data Chevron down icon Chevron up icon
Building an E-Commerce Store – Browsing Products Chevron down icon Chevron up icon
Building an E-Commerce Store – Adding a Checkout Chevron down icon Chevron up icon
Using Vue Dev Tools and Testing Your SPA Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.