Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Vue.js 2
Learning Vue.js 2

Learning Vue.js 2: Learn how to build amazing reactive web applications easily with Vue.js

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning Vue.js 2

Chapter 1. Going Shopping with Vue.js

"Vue.js is a JavaScript framework for building astonishing web applications. Vue.js is a JavaScript library for creating web interfaces. Vue.js is a tool that leverages the use of MVVM architecture."

Simplified JavaScript Jargon suggests that Vue.js is a JavaScript library for creating user interfaces (Views) based on underlying data models ( http://jargon.js.org/_glossary/VUEJS.md ).

The official Vue.js website ( https://vuejs.org/ ) just some months ago stated that Vue.js were reactive components for modern web interfaces.

Going Shopping with Vue.js

Now it states that Vue.js is a progressive JavaScript framework:

Going Shopping with Vue.js

So what is Vue.js after all? Framework? Tool? Library? Should it be used for building full-stack web applications or just for adding some special functionality? Should I switch from my favorite framework to it? If yes, why? Can I use it alongside other tools in my project? What advantages it might bring?

In this chapter, we will try to find the answers to all these questions. We will slightly touch Vue.js and use it within some small and simple examples.

More specifically, we will do the following:

  • Learn what Vue.js is, its important parts, and its history
  • Learn what projects use Vue.js
  • Build a simple shopping list using Vue.js and compare the implementation to the jQuery implementation of the same application
  • Build a simple Pomodoro timer using Vue.js
  • Enjoy a small and simple exercise

Buzzwords

There will be lots of buzzwords, abbreviations, and other hipster combinations of letters in this book. Please do not be afraid of them. I can tell you more but, for the most part of things you need to do using Vue.js or any other framework, you do not need to know them all by heart! But, in any case, let us leave the thesaurus here so that you become confused with terminology at any point of the book, you can come back here and have a look:

  • Application state: This is a global centralized state of the application. The data in this state is initialized when the application is started. This data can be accessed by any application's component; however, it cannot be changed easily by them. Each item of the state has an attached mutation that can be dispatched on special events occurring inside the application's components.
  • Bootstrap: This is a project that provides a set of styles and JavaScript tools for developing a responsive and nice application without having to think a lot about CSS.
  • Content Distribution Network (CDN): This is a special server whose aim is to deliver data to the users with high availability and high performance. People and companies who develop frameworks like to distribute them via CDNs because they allow them just to point out the CDN's URL in the installation instructions. Vue.js is hosted in npmcdn ( https://npmcdn.com/ ), which is a reliable and global network for the things that are published to the npm.
  • Components: These are the pieces of the application with their own data and View that can be reused through the application, acting as a brick from which the house is being built.
  • Cascading Style Sheets (CSS): This is a set of styles to apply to the HTML document to make it nice and beautiful.
  • Declarative Views: These are the Views that provide a way of direct data binding between plain JavaScript data models and the representation.
  • Directives: These are special HTML elements attributes in Vue.js that allow data binding in different ways.
  • Document Object Model (DOM): This is a convention for representing nodes in markup languages such as HTML, XML, and XHTML. The nodes of the documents are organized into a DOM tree. When someone says interacting with DOM, it is just their fancy way of saying interacting with HTML elements.
  • npm: This is a package manager for JavaScript and allows searching, installing, and managing JavaScript packages.
  • Markdown: This is a human-friendly syntax that allows web writers to write their text without worrying about styles and HTML tags. Markdown files have a .md extension.
  • Model View ViewModel (MVVM): This is an architectural pattern whose central point is a ViewModel that acts as a bridge between the View and the data model, allowing the data flow between them.
  • Model View Controller (MVC): This is an architectural pattern. It allows separating Views from Models and from the way that information flows from Views to Models, and vice versa.
  • One-way data binding: This is the type of data binding where the changes in the data model are automatically propagated to the View layer, but not vice versa.
  • Rapid prototyping: In the Web, this is a technique of easily and rapidly building the mockups of the user interface, including some basic user interaction.
  • Reactivity: In the Web, this is actually the immediate propagation of any changes of data to the View layer.
  • Two-way data binding: This is the type of data binding where the changes in the data model are automatically propagated to the View layer, and the changes that happen in the View layer are immediately reflected in the data model.
  • User interface (UI): This is a set of visual components that allow the user to communicate with the application.
  • Vuex: This is an architecture for Vue applications and allows simple management of the application state.

Vue.js history

When, Evan You, Vue.js creator ( http://evanyou.me/ ), was working at Google Creative Labs on one of the projects, they needed to fast prototype a rather big UI interface. Writing a lot of repeated HTML was clearly time- and resource-consuming, and that's why Evan started looking for some already existing tool for this purpose. To his surprise, he discovered that there was no tool, library, or framework that could fit exactly into the purpose of rapid prototyping! At that time, Angular was widely used, React.js was just starting, and frameworks such as Backbone.js were used for large-scale applications with MVC architecture. For the kind of project that needed something really flexible and lightweight just for quick UI prototyping, neither of these complex frameworks were adequate.

When you realize that something cool does not exist and you are able to create it—just do it!

Note

Vue.js was born as a tool for rapid prototyping. Now it can be used to build complex scalable reactive web applications.

That was what Evan did. That is how he came to the idea of creating a library that would help in rapid prototyping by offering an easy and flexible way of reactive data binding and reusable components.

Like every good library, Vue.js has been growing and evolving, thus providing more features than it was promising from the beginning. Currently, it provides an easy way of attaching and creating plugins, writing and using mixins, and overall adding custom behavior. Vue can be used in such a flexible way and is so nonopinionated of the application structuring that it definitely can be considered as a framework capable of supporting the end-to-end building of complex web applications.

The most important thing about Vue.js

Vue.js allows you to simply bind your data models to the representation layer. It also allows you to easily reuse components throughout the application.

You don't need to create special models or collections and to register events object in there. You don't need to follow some special syntax. You don't need to install any of never-ending dependencies.

Your models are plain JavaScript objects. They are being bound to whatever you want in your Views (text, input text, classes, attributes, and so on), and it just works.

You can simply add the vue.js file into your project and use it. Alternatively, you can use vue-cli with Webpack and Browserify family, which not only bootstraps the whole project but also supports hot reloading and provides developer tools.

You can separate the View layer from styles and JavaScript logic or you can put it alltogether into the same Vue file and build your components' structure and logic in the same place. There is plugin support for all modern and commonly used IDEs.

You can use whatever preprocessors you want, and you can use ES2015. You can use it alongside your favorite framework you have been developing in, or you can use it itself. You can use it just to add a small functionality, or you can use the whole Vue ecosystem to build complex applications.

If you want to check how it compares to other frameworks, such as Angular or React, then please visit  http://vuejs.org/guide/comparison.html .

If you want to check out all the amazing things about Vue.js, then you are more than welcome to visit  https://github.com/vuejs/awesome-vue .

Let's go shopping!

I don't know how but I can feel that your weekend is close and that you are starting to think about going shopping to buy the needed groceries for the next week. Unless you are a genius who is able to maintain the whole list in your head or you are a modest person who does not need so much, you probably make a shopping list before going shopping. Maybe you even use some app for that. Now, I ask you: why not use your own app? How do you feel about creating and designing it? Let's do that! Let's create our own shopping list application. Let's start by creating a rapid prototype for it. It's a really easy task—build an interactive prototype for the shopping list.

It should show the list and allow us to add and remove the items. Actually, it's very similar to a ToDo list. Let's start doing it using classic HTML + CSS + JS + jQuery approach. We will also use the Bootstrap framework ( http://getbootstrap.com/ ) to make things a little bit more beautiful without having to write extensive CSS code. (Yes, because our book is not about CSS and because making things with Bootstrap is so crazily easy!)

Implementing a shopping list using jQuery

Probably, your code will end up looking as something like the following:

Here is the HTML code:

<div class="container"> 
  <h2>My Shopping List</h2> 
  <div class="input-group"> 
    <input placeholder="add shopping list item"        
      type="text" class="js-new-item form-control"> 
    <span class="input-group-btn"> 
      <button @click="addItem" class="js-add btn btn-default"          
        type="button">Add!</button> 
    </span> 
  </div> 
  <ul> 
    <li> 
      <div class="checkbox"> 
        <label> 
          <input class="js-item" name="list"              
            type="checkbox"> Carrot 
        </label> 
      </div> 
    </li> 
    <li> 
      <div class="checkbox"> 
        <label> 
          <input class="js-item" name="list" type="checkbox"> Book 
        </label> 
      </div> 
    </li> 
    <li class="removed"> 
      <div class="checkbox"> 
        <label> 
          <input class="js-item" name="list" type="checkbox"              
            checked> Gift for aunt's birthday 
        </label> 
      </div> 
    </li> 
  </ul> 
</div> 

Here is the CSS code:

.container { 
  width: 40%; 
  margin: 20px auto 0px auto; 
} 
 
.removed { 
  color: gray; 
} 
 
.removed label { 
  text-decoration: line-through; 
} 
 
ul li { 
  list-style-type: none; 
} 

Here is the JavaScript/jQuery code:

$(document).ready(function () { 
  /** 
   * Add button click handler 
   */ 
  function onAdd() { 
    var $ul, li, $li, $label, $div, value; 
 
    value = $('.js-new-item').val(); 
    //validate against empty values 
    if (value === '') { 
      return; 
    } 
    $ul = $('ul'); 
    $li = $('<li>').appendTo($ul); 
    $div = $('<div>') 
        .addClass('checkbox') 
        .appendTo($li); 
    $label = $('<label>').appendTo($div); 
    $('<input>') 
        .attr('type', 'checkbox') 
        .addClass('item') 
        .attr('name', 'list') 
        .click(toggleRemoved) 
        .appendTo($label); 
    $label 
        .append(value); 
    $('.js-new-item').val(''); 
  } 
 
  /** 
   * Checkbox click handler - 
   * toggles class removed on li parent element 
   * @param ev 
   */ 
  function toggleRemoved(ev) { 
    var $el; 
 
    $el = $(ev.currentTarget); 
    $el.closest('li').toggleClass('removed'); 
  } 
 
  $('.js-add').click(onAdd); 
  $('.js-item').click(toggleRemoved); 
}); 

Tip

Downloading the example code Detailed steps to download the code bundle are mentioned in the Preface of this book. The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Vue.js-2. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

If you open the page in a browser, you will probably see something like the following:

Implementing a shopping list using jQuery

Shopping list implementation using the HTML + CSS + jQuery approach

Please have a look at JSFiddle at https://jsfiddle.net/chudaol/u5pcnLw9/2/ .

As you can see, it is a very basic piece of HTML code that contains an unordered list of elements, where each element is presented with a checkbox and a text—an input for the user text and the Add! button. Each time the Add! button is clicked, the content of the text input is transformed into a list entry and appended to the list. When the checkbox of any item is clicked, the state of an entry is toggled from to to buy (unchecked) to bought (checked).

Let's also add a feature that allows us to change the title of the list (it might become useful if we end up implementing multiple shopping lists in the application).

So, we will end up with some extra markup and some more jQuery event listeners and handlers:

<div class="container"> 
  <h2>My Shopping List</h2> 
  <!-- ... --> 
  <div class="footer"> 
    <hr/> 
    <em>Change the title of your shopping list here</em> 
    <input class="js-change-title" type="text"
      value="My Shopping List"/> 
  </div> 
</div> 
 
//And javascript code: 
function onChangeTitle() { 
  $('h2').text($('.js-change-title').val()); 
} 
$('.js-change-title').keyup(onChangeTitle); 

Check JSFiddle at https://jsfiddle.net/chudaol/47u38fvh/3/ .

Implementing a shopping list using Vue.js

This was a very simple example. Let's try to implement it step-by-step using Vue.js. There are plenty of ways of including vue.js into your project, but in this chapter, we will include it just by adding the JavaScript Vue file from the CDN:

<script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js">  </script> 

So, let's start by rendering a list of elements.

Create the HTML file and add the following markup:

<div id="app" class="container"> 
  <h2>{{ title }}</h2> 
  <ul> 
    <li>{{ items[0] }}</li> 
    <li>{{ items[1] }}</li> 
  </ul> 
</div> 

Now add the following JavaScript code:

var data = { 
  items: ['Bananas', 'Apples'], 
  title: 'My Shopping List' 
}; 
 
new Vue({ 
  el: '#app', 
  data: data 
}); 

Open it in the browser. You will see that the list is rendered:

Implementing a shopping list using Vue.js

Shopping list implemented using Vue.js

Let's analyze this example. The Vue application code starts with the new Vue keyword. How do we bind the piece of markup to the application data? We pass to the Vue instance the DOM element that must be bound to it. Any other markup in the page will not be affected and will not recognize Vue's magic.

As you can see, our markup is wrapped into the #app element and is passed as a first argument in the map of Vue options. The data argument contains the objects that are being used inside the markup using double curly brackets ({{}}) . You will probably find this annotation very easy to understand if you are familiar with templating preprocessors (for example, handlebars; for more information, visit http://handlebarsjs.com/ ).

So what?—you're probably exclaiming. What are you going to teach me? How to use templating preprocessors? Thank you very much, but I would be better off having some beers and watching football.

Stop, dear reader, don't go, just grab your beer and let's continue our example. You'll see that it'll be lots of fun!

Analyzing data binding using developer tools

Let's see data binding in action. Open your browser's developer tools, find your JavaScript code, and add a breakpoint at the start of the script. Now analyze how the data objects look before and after the Vue application is initialized. You see, it changed a lot. Now the data object is prepared to the reactive data binding:

Analyzing data binding using developer tools

The data object before and after the Vue object initialization

Now if we change the title property of the data object from the developer tools console (we can do it because our data is a global object), it will be reflected automatically in the title on the page:

Analyzing data binding using developer tools

Data binding: changing object properties affects the View immediately

Bringing user input to the data with two-way binding

So, in our example, we were able to bring the data from the plain JavaScript data model to the page. We provided it a sort of a flight from the application code to the page. Don't you think that it would be nice if we could offer a two-way flight to our data?

Let's see now how we can achieve two-way data binding and how we can change the value of a data property from the page.

Copy the HTML markup for the title, change the input from the first jQuery example, and add the attribute v-model="title" to the input element.

Tip

Have you already heard about directives in Vue.js? Congratulations, you've just used one! Actually, the v-model attribute is a directive of Vue.js that provides two-way data binding. You can read more about it at the official Vue page: http://vuejs.org/api/#v-model .

Now, the HTML code for our shopping list application code looks like the following:

<div id="app" class="container"> 
  <h2>{{ title }}</h2> 
  <ul> 
    <li>{{ items[0] }}</li> 
    <li>{{ items[1] }}</li> 
  </ul> 
  <div class="footer"> 
    <hr/> 
    <em>Change the title of your shopping list here</em> 
    <input v-model="title"/> 
  </div> 
</div> 

And that's it!

Refresh the page now and modify the input. You'll see the title automatically being updated as you type:

Bringing user input to the data with two-way binding

Data binding: changing the text bound to the model's property affects the text bound to the same property immediately

So, everything is nice; however, this example just grabs the two item elements and renders them as list items. We want it to render the list of items independently of the list size.

Rendering the list of items using the v-for directive

So, we need some mechanism to iterate through the items array and to render each item in our <ul> element.

Fortunately, Vue.js provides us with a nice directive for iterating through iterative JavaScript data structures. It is called v-for. We will use it in the list item <li> element. Modify the markup of the list so that it looks like the following:

  <ul> 
    <li v-for="item in items">{{ item }}</li> 
  </ul> 

Note

You will learn other nice directives such as v-if, v-else, v-show, v-on, v-bind, and so on in this book, so keep reading.

Refresh the page and have a look. The page remains the same. Now, try to push an item into the array of items from the developer tools console. Try to pop them as well. You will not be surprised to see that the items array manipulations are immediately reflected on the page:

Rendering the list of items using the v-for directive

Data binding: changing an array affects lists based on it immediately

So, now we have a list of items that is rendered on a page with just one line of the markup. However, we still need these items to have a checkbox that allows us to check the already bought items or uncheck them when needed.

Check and uncheck shopping list items

To achieve this behavior, let's slightly modify our items array by changing our string items and transforming them into the objects with two properties, text and checked (to reflect the state), and let's modify the markup to add a checkbox to each item.

So our JavaScript code for the data declaration will look like the following:

var data = { 
  items: [{ text: 'Bananas', checked: true },    
          { text: 'Apples',  checked: false }], 
  title: 'My Shopping List', 
  newItem: '' 
}; 

And our list markup will look like this:

<ul> 
  <li v-for="item in items" v-bind:class="{ 'removed':      
    item.checked }"> 
    <div class="checkbox"> 
      <label> 
        <input type="checkbox" v-model="item.checked"> {{            
          item.text }} 
      </label> 
    </div> 
  </li> 
</ul>  

Refresh the page and check that the checked property of the items checkbox, and the removed class of each list item, <li>, is bound to the checked Boolean state of the items. Play around and try to click checkboxes to see what happens. Isn't it nice that just with two directives we are able to propagate the state of the items and change the class of the corresponding <li> HTML element?

Adding new shopping list items using the v-on directive

So now we just need a small addition to our code to be able to actually add shopping list items. To achieve that, we will add one more object to our data and call it newItem. We'll also add a small method that pushes new item to the items array. And we'll call this method from the markup page using the v:on directive used on the HTML input element that will be used for the new item and on the button used to click to add a new item.

So our JavaScript code will look like the following:

var data = { 
  items: [{ text: 'Bananas', checked: true },    
          { text: 'Apples', checked: false }], 
  title: 'My Shopping List', 
  newItem: '' 
}; 
new Vue({ 
  el: '#app', 
  data: data, 
  methods: { 
    addItem: function () { 
      var text; 
 
      text = this.newItem.trim(); 
      if (text) { 
        this.items.push({ 
          text: text, 
          checked: false 
        }); 
        this.newItem = ''; 
      } 
    } 
  } 
}); 

We added a new property to the data object called newItem. Then we added a new section called methods to our Vue initialization options object and added the addItem method to this section. All the data properties are accessible in the methods section via the this keyword. Thus, in this method, we just get this.newItem and push it into the  this.items array. Now we must bind the call to this method to some user action. As it has already been mentioned, we will use the v-on directive and apply it to the enter keyup on the new item input and to the Add! button click.

So add the following markup before our list of items:

<div class="input-group"> 
  <input v-model="newItem" v-on:keyup.enter="addItem"      
    placeholder="add shopping list item" type="text" class="form-      
    control"> 
  <span class="input-group-btn"> 
    <button v-on:click="addItem" class="btn btn-default"            
      type="button">Add!</button> 
  </span> 
</div> 

Note

The v-on directive attaches an event listener to the elements. The shortcut is the @ sign. So, instead of writing v-on:keyup="addItem", you can write @keyup="addItem". You can read more about the v-on directive on the official documentation site at http://vuejs.org/api/#v-on .

Let's finalize. The whole code now looks like the following:

Here is the HTML code:

<div id="app" class="container"> 
  <h2>{{ title }}</h2> 
  <div class="input-group"> 
    <input v-model="newItem" @keyup.enter="addItem"        
      placeholder="add shopping list item" type="text" 
      class="form-control"> 
  <span class="input-group-btn"> 
    <button @click="addItem" class="btn btn-default"        
      type="button">Add!</button> 
  </span> 
  </div> 
  <ul> 
    <li v-for="item in items" :class="{ 'removed': item.checked      
      }"> 
      <div class="checkbox"> 
        <label> 
          <input type="checkbox" v-model="item.checked"> {{              
            item.text }} 
        </label> 
      </div>     
    </li> 
  </ul> 
  <div class="footer hidden"> 
    <hr/> 
    <em>Change the title of your shopping list here</em> 
    <input v-model="title"/> 
  </div> 
</div> 

Here is the JavaScript code:

var data = { 
  items: [{ text: 'Bananas', checked: true },    
          { text: 'Apples', checked: false }], 
  title: 'My Shopping List', 
  newItem: '' 
}; 
 
new Vue({ 
  el: '#app', 
  data: data, 
  methods: { 
    addItem: function () { 
      var text; 
 
      text = this.newItem.trim(); 
      if (text) { 
        this.items.push({ 
          text: text, 
          checked: false 
        }); 
        this.newItem = ''; 
      } 
    } 
  } 
}); 

Here's a link to JSFiddle: https://jsfiddle.net/chudaol/vxfkxjzk/3/ .

Using Vue.js in an existing project

I can feel now that you have seen how easy is to bind the properties of the model to the presentation layer and you are already starting to think about how it can be used in your existing project. But then you think: hell, no, I need to install some things, run npm install, change the project's structure, add directives, and change the code.

And here I can tell you: no! No installs, no npms, just grab the vue.js file, insert it into your HTML page, and use it. That's all, no structure changes, no architectural decisions, no discussions. Just use it. I will show you how we used it at EdEra ( https://www.ed-era.com ) to include a small "check yourself" functionality at the end of a GitBook chapter.

EdEra is a Ukraine-based online educational project whose aim is to transform the whole educational system into something modern, online, interactive, and fun. Actually, I am a co-founder and the chief technical officer of this young nice project, being responsible for the whole technical part of the thing. So, in EdEra, we have some online courses built on top of the open EdX platform ( https://open.edx.org/ ) and some interactive educational books built on top of the great GitBook framework ( http://www.gitbook.com ). Basically, GitBook is a platform based on top of the Node.js technology stack. It allows someone with basic knowledge of the markdown language and basic Git commands to write books and host them in the GitBook servers. EdEra's books can be found at http://ed-era.com/books (beware, they are all in Ukrainian).

Let's see what we have done in our books using Vue.js.

At some point, I decided to include a small quiz at the end of the chapter about personal pronouns in the book that teaches English. Thus, I've included the vue.js JavaScript file, edited the corresponding .md file, and included the following HTML code:

<div id="pronouns"> 
    <p><strong>Check yourself :)</strong></p> 
    <textarea class="textarea" v-model="text" v-      
      on:keyup="checkText"> 
        {{ text }} 
    </textarea><i  v-bind:class="{ 'correct': correct,      
      'incorrect': !correct }"></i> 
</div> 

Then I added a custom JavaScript file, where I've included the following code:

$(document).ready(function() { 
  var initialText, correctText; 
 
  initialText = 'Me is sad because he is more clever than I.'; 
  correctText = 'I am sad because he is more clever than me.'; 
 
  new Vue({ 
    el: '#pronouns', 
    data: { 
      text: initialText, 
      correct: false 
    }, 
    methods: { 
      checkText: function () { 
        var text; 
        text = this.text.trim(); 
        this.correct = text === correctText; 
      } 
    } 
  }); 
}); 

Note

You can check this code at this GitHub page: https://github.com/chudaol/ed-era-book-english . Here's a code of a page written in markdown with inserted HTML: https://github.com/chudaol/ed-era-book-english/blob/master/2/osobovi_zaimenniki.md . And here's a JavaScript code: https://github.com/chudaol/ed-era-book-english/blob/master/custom/js/quiz-vue.js . You can even clone the repository and try it locally using gitbook-cli ( https://github.com/GitbookIO/gitbook/blob/master/docs/setup.md ).

Let's have a look at this code. You have probably already detected the parts that you have already seen and even tried:

  • The data object contains two properties:
    • The string property text
    • The Boolean property correct
  • The checkText method just grabs the text property, compares it with the correct text, and assigns the value to the correct value
  • The v-on directive calls the checkText method on keyup
  • The v-bind directive binds the class correct to the correct property

Here is how the code looks in my IDE:

Using Vue.js in an existing project

Using Vue in a markdown-driven project

And next is what it looks like in the browser:

Using Vue.js in an existing project

Vue.js in action inside the GitBook page

Using Vue.js in an existing project

Vue.js in action inside the GitBook page

Check it out at http://english.ed-era.com/2/osobovi_zaimenniki.html .

Amazing, right? Pretty simple, pretty reactive!

Vue.js 2.0!

At the time of writing, Vue.js 2.0 was announced ( https://vuejs.org/2016/04/27/announcing-2.0/ ). Check the following links in this regard:

The second version of Vue.js has some considerable differences comparing to its predecessor, starting from the way that data binding is being handled and moving to its API. It uses lightweight virtual DOM implementation for rendering, supports server-side rendering, and is faster and leaner.

At the time of writing, Vue 2.0 was in an early alpha stage. Do not worry, though. All the examples that we will cover in this book are based on the latest stable version of Vue 2.0 and are fully compatible with the both the versions.

Projects using Vue.js

Probably, at this time, you are wondering what projects are out there that are built on top of Vue.js, or use it as a part of their codebase. There are a lot of nice open source, experimental, and enterprise projects using it. The complete and constantly updated list of these projects can be found at https://github.com/vuejs/awesome-vue#projects-using-vuejs .

Let's have a look at some of them.

Grammarly

Grammarly ( https://www.grammarly.com/ ) is a service that helps you write English correctly. It has several apps, one of them is a simple Chrome extension that just checks any text input that you fill in. Another one is an online editor that you can use to check big chunks of text. This editor is built using Vue.js! The following is a screenshot of this text being edited in the online editor of Grammarly:

Grammarly

Grammarly: a project that is built on top of Vue.js

Optimizely

Optimizely ( https://www.optimizely.com/ ) is a service that helps you test, optimize, and personalize your websites. I've used the Packt site to create an Optimizely experiment and to check out Vue.js in action in this resource. It looks like the following:

Optimizely

Optimizely: a project that is built on top of Vue.js

Hovering around with the mouse gives us the possibility of opening a context menu that allows different manipulations with the page data, including the simplest one, text editing. Let's try this one:

Optimizely

Using Optimizely and watching Vue.js in action

The text box is opened. When I type in it, the text in the title is reactively changed. We saw and implemented it using Vue.js:

Optimizely

Using Optimizely and watching Vue.js in action

FilterBlend

FilterBlend ( https://github.com/ilyashubin/FilterBlend ) is an open source playground for the CSS background-blend-mode and filter properties.

You can load your images and combine blending with filters.

If you want to give FilterBlend a try, you can install it locally:

  1. Clone the repository:
    git clone https://github.com/ilyashubin/FilterBlend.git
    
  2. Enter the FilterBlend directory:
    cd FilterBlend
    
  3. Install the dependencies:
    npm install
    
  4. Run the project:
    gulp
    

Open your browser on localhost:8000 and play around. You can see that once you change something in the menu on the right, it is immediately propagated to the images on the left side. All this functionality is achieved using Vue.js. Check the code on GitHub.

FilterBlend

FilterBlend: a project built on top of Vue.js

PushSilver

PushSilver ( https://pushsilver.com ) is a nice and simple service for busy people to create simple invoices. It allows creating invoices, sending and resending them to the clients, and keeping tracking of them. It was created by a developer doing freelance consultancy and being tired of having to create invoices each time for each small project. This tool works well and it was built using Vue.js:

PushSilver

PushSilver: invoice managing application built on top of Vue.js

PushSilver

PushSilver: invoice managing application built on top of Vue.js

Book roadmap

This book, like most part of technical books, is organized in such a way that you do not need to read it from beginning to end. You can choose the parts that interest you the most and skip the rest.

This book is organized as follows:

  • If you are reading this, there's no need to specify what is going on in the first chapter.
  • Chapter 2, Fundamentals - Installing and Using, is pretty theoretical and will explain what's going on behind the scenes of Vue.js and its main parts. So, if you are not into theory and want to put your hands into coding, you are free to skip this part. In this part, we will also go through the installation and setup process.
  • From the third to the eighth chapter, we'll explore the main features of Vue.js while building the application:
    • In Chapter 3, Components - Understanding and Using, we will introduce Vue components and apply this knowledge to our application.
    • In Chapter 4, Reactivity - Binding Data to Your Application, we will use all the data binding mechanisms provided by Vue.
    • In Chapter 5, Vuex - Managing State in Your Application, we will introduce the Vuex state management system and explain how to use it in our applications.
    • In Chapter 6, Plugins - Building Your House with Your Own Bricks, we will learn how to create and use plugins for Vue applications to enrich their functionality.
    • In Chapter 7, Testing - Time to Test What We Have Done so Far!, we will cover and explore custom directives of Vue.js and create some in our application.
    • In Chapter 8, Deploying - Time to Go Live!, we will learn how to test and deploy JavaScript application written in Vue.js.
  • In Chapter 9, What Is Next?, we'll summarize what we've learned and see what we can do next.

Let's manage time!

At this point of time, I already know that you are so, so, so enthusiastic with this book that you want to read it to the end without stopping. But this is not right. We should manage our time and give us some time to work and some time to rest. Let's create a small application that implements a Pomodoro technique timer so that it can help us in our working time management.

Note

The Pomodoro technique is a time management technique named after the kitchen tomato timer (in fact, Pomodoro means tomato in Italian). This technique consists of breaking down the working time into small intervals separated by short breaks. Read more about the Pomodoro technique on the official site: http://pomodorotechnique.com/ .

Thus, our goal is very simple. We just have to create a very simple time counter that will decrement untill the end of the working interval and then restart and decrement till the end of the resting time and so on.

Let's do that!

We will introduce two Vue data variables, minute and second, which will be displayed on our page. The main method on each second will decrement second; it will decrement minute when second becomes 0; and when both minute and second variables come to 0, the application should toggle between working and resting interval:

Our JavaScript code will look like the following:

const POMODORO_STATES = { 
  WORK: 'work', 
  REST: 'rest' 
}; 
const WORKING_TIME_LENGTH_IN_MINUTES = 25; 
const RESTING_TIME_LENGTH_IN_MINUTES = 5; 
 
new Vue({ 
  el: '#app', 
  data: { 
    minute: WORKING_TIME_LENGTH_IN_MINUTES, 
    second: 0, 
    pomodoroState: POMODORO_STATES.WORK, 
    timestamp: 0 
  }, 
  methods: { 
    start: function () { 
      this._tick(); 
      this.interval = setInterval(this._tick, 1000); 
    }, 
    _tick: function () { 
      //if second is not 0, just decrement second 
      if (this.second !== 0) { 
        this.second--; 
        return; 
      } 
      //if second is 0 and minute is not 0,        
      //decrement minute and set second to 59 
      if (this.minute !== 0) { 
        this.minute--; 
        this.second = 59; 
        return; 
      } 
      //if second is 0 and minute is 0,        
      //toggle working/resting intervals 
      this.pomodoroState = this.pomodoroState ===        
      POMODORO_STATES.WORK ? POMODORO_STATES.REST :        
      POMODORO_STATES.WORK; 
      if (this.pomodoroState === POMODORO_STATES.WORK) { 
        this.minute = WORKING_TIME_LENGTH_IN_MINUTES; 
      } else { 
        this.minute = RESTING_TIME_LENGTH_IN_MINUTES; 
      } 
    } 
  } 
}); 

In our HTML code, let's create two placeholders for minute and second, and a start button for our Pomodoro timer:

<div id="app" class="container"> 
  <h2> 
    <span>Pomodoro</span> 
    <button  @click="start()"> 
      <i class="glyphicon glyphicon-play"></i> 
    </button> 
  </h2> 
  <div class="well"> 
    <div class="pomodoro-timer"> 
      <span>{{ minute }}</span>:<span>{{ second }}</span> 
    </div> 
  </div> 
</div> 

Again, we are using Bootstrap for the styling, so our Pomodoro timer looks like the following:

Let's manage time!

Countdown timer built with Vue.js

Our Pomodoro is nice, but it has some problems:

  • First of all, we don't know which state is being toggled. We don't know if we should work or rest. Let's introduce a title that will change each time the Pomodoro state is changed.
  • Another problem is inconsistent display of minutes and seconds numbers. For example, for 24 minutes and 5 seconds, we would like to see 24:05 and not 24:5. Let's fix it introducing computed values in our application data and displaying them instead of normal values.
  • Yet another problem is that our start button can be clicked over and over again, which creates a timer each time it's clicked. Try to click it several times and see how crazy your timer goes. Let's fix it by introducing start, pause, and stop buttons, apply application states to them, and disable buttons to the state accordingly.

Toggle the title by using computed properties

Let's start by fixing the first problem by creating computed property title and using it in our markup.

Note

Computed properties are the properties inside the data object that allow us to avoid blowing up the template with some extra logic. You can find more information about computed properties on the official documentation site: http://vuejs.org/guide/computed.html .

Add the computed section in the Vue options object and add the property title there:

data: { 
  //... 
}, 
computed: { 
  title: function () { 
    return this.pomodoroState === POMODORO_STATES.WORK ? 'Work!' :      
    'Rest!' 
  } 
}, 
methods: { 
//... 

And now just use the following property as it was a normal Vue data property in your markup:

  <h2> 
    <span>Pomodoro</span> 
    <!--!> 
  </h2> 
  <h3>{{ title }}</h3> 
  <div class="well"> 

And voilà! Now we have a title that changes each time the Pomodoro state is being toggled:

Toggle the title by using computed properties

Automatic change of the title based on the state of the timer

Nice, isn't it?

Left-pad time values using computed properties

Now let's apply the same logic for left padding our minute and second numbers. Let's add two computed properties, min and sec, in our computed section in the data options and apply the simple algorithm to pad the numbers with 0 on the left. Of course, we could use a famous left-pad project ( https://github.com/stevemao/left-pad ), but to keep things simple and not to break the whole Internet ( http://www.theregister.co.uk/2016/03/23/npm_left_pad_chaos/ ), let's apply a simple logic of our own:

computed: { 
  title: function () { 
    return this.pomodoroState === POMODORO_STATES.WORK ? 'Work!' :      
    'Rest!' 
  }, 
  min: function () { 
    if (this.minute < 10) { 
      return '0' + this.minute; 
    } 
 
    return this.minute; 
  }, 
  sec: function () { 
    if (this.second < 10) { 
      return '0' + this.second; 
    } 
 
    return this.second; 
  } 
} 

And let's use these properties instead of minute and second in our HTML code:

   <div class="pomodoro-timer"> 
    <span>{{ min }}</span>:<span>{{ sec }}</span> 
   </div> 

Refresh a page and check how beautiful our numbers are now:

Left-pad time values using computed properties

Left padding using computed properties in Vue.js

Keep state with start, pause, and stop buttons

So, to fix the third problem, let's introduce three application states, started, paused, and stopped, and let's have three methods that would allow us to permute over these states. We already have the method that starts the application, so we just add the logic there to change the state to started. We also add two additional methods, pause and stop, which would pause the timer and change to the corresponding application state:

const POMODORO_STATES = { 
  WORK: 'work', 
  REST: 'rest' 
}; 
const STATES = { 
  STARTED: 'started', 
  STOPPED: 'stopped', 
  PAUSED: 'paused' 
}; 
//<...> 
new Vue({ 
  el: '#app', 
  data: { 
    state: STATES.STOPPED, 
    //<...> 
  }, 
  //<...> 
  methods: { 
    start: function () { 
      this.state = STATES.STARTED; 
      this._tick(); 
      this.interval = setInterval(this._tick, 1000); 
    }, 
    pause: function () { 
      this.state = STATES.PAUSED; 
      clearInterval(this.interval); 
    }, 
    stop: function () { 
      this.state = STATES.STOPPED; 
      clearInterval(this.interval);  
      this.pomodoroState = POMODORO_STATES.WORK; 
      this.minute = WORKING_TIME_LENGTH_IN_MINUTES; 
      this.second = 0; 
    }, 
    //<...> 
  } 
}); 

And, let's add two buttons to our HTML code and add the click listeners that call the corresponding methods:

    <button :disabled="state==='started'"
@click="start()"> 
      <i class="glyphicon glyphicon-play"></i> 
    </button> 
    <button :disabled="state!=='started'"       
      @click="pause()"> 
      <i class="glyphicon glyphicon-pause"></i> 
    </button> 
    <button :disabled="state!=='started' && state !== 'paused'"      
       @click="stop()"> 
      <i class="glyphicon glyphicon-stop"></i> 
    </button> 

Now our application looks nice and allows us to start, pause, and stop the timer:

Keep state with start, pause, and stop buttons

Toggling start, stop, and pause buttons according to the application state

Check what the whole code looks like in JSFiddle at  https://jsfiddle.net/chudaol/b6vmtzq1/1/.

After so much work and so many of new terms and knowledge, you certainly deserve a kitten! I also love kittens, so here you have a random kitten from the awesome site http://thecatapi.com/ :

Keep state with start, pause, and stop buttons

Exercise

At the end of this chapter, I would like to propose a small exercise. The Pomodoro timer that we built earlier in the chapters is, without any doubt, great, but it still lacks some nice features. A really nice thing that it could provide would be showing random kittens from    http://thecatapi.com/ during resting time. Can you implement this? Of course you can! But please do not confuse resting with working time! I am almost sure that your project manager will not like it much if you stare at kittens instead of working.

The solution to this exercise can be found in Appendix, Solutions to Exercises.

Summary

I am very glad that you have reached this point, this means that you already know what Vue.js is, and if someone asks you whether it is a tool, a library, or a framework, you certainly will find an answer. You also know how to start an application using Vue.js and you know how to use Vue's features in an already existing project. You played around with some really nice projects that are written in Vue.js and you started developing some of your own! Now you do not just go shopping, now you go shopping with a shopping list created by you using Vue.js! Now you don't need to steal your tomato timer from the kitchen to use it as a Pomodoro timer while working; you can use your own digital Pomodoro timer made with Vue.js. And, last but not the least, now you can insert random kittens in your JavaScript application also using Vue.js.

In the next chapter, we will cover the behind the scenes of Vue, how and why does it work, and the architectural patterns it uses. Each of the concepts will be wrapped up with an example to demonstrate it. Then we will be ready to put our hands deep into the code and to improve our applications taking them to the state of awesomeness.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to propagate DOM changes across the website without writing extensive jQuery callbacks code.
  • Learn how to achieve reactivity and easily compose views with Vue.js and understand what it does behind the scenes.
  • Explore the core features of Vue.js with small examples, learn how to build dynamic content into preexisting web applications, and build Vue.js applications from scratch.

Description

Vue.js is one of the latest new frameworks to have piqued the interest of web developers due to its reactivity, reusable components, and ease of use. This book shows developers how to leverage its features to build high-performing, reactive web interfaces with Vue.js. From the initial structuring to full deployment, this book provides step-by-step guidance to developing an interactive web interface from scratch with Vue.js. You will start by building a simple application in Vue.js which will let you observe its features in action. Delving into more complex concepts, you will learn about reactive data binding, reusable components, plugins, filters, and state management with Vuex. This book will also teach you how to bring reactivity to an existing static application using Vue.js. By the time you finish this book you will have built, tested, and deployed a complete reactive application in Vue.js from scratch.

Who is this book for?

This book is perfect for novice web developer seeking to learn new technologies or frameworks and also for webdev gurus eager to enrich their experience. Whatever your level of expertise, this book is a great introduction to the wonderful world of reactive web apps.

What you will learn

  • Build a fully functioning reactive web application in Vue.js from scratch.
  • The importance of the MVVM architecture and how Vue.js compares with other frameworks such as Angular.js and React.js.
  • How to bring reactivity to an existing static application using Vue.js.
  • How to use plugins to enrich your applications.
  • How to develop customized plugins to meet your needs.
  • How to use Vuex to manage global application's state.
Estimated delivery fee Deliver to Hungary

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 13, 2016
Length: 334 pages
Edition : 1st
Language : English
ISBN-13 : 9781786469946
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Hungary

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Dec 13, 2016
Length: 334 pages
Edition : 1st
Language : English
ISBN-13 : 9781786469946
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
Vue.js 2 and Bootstrap 4 Web Development
€36.99
Learning Vue.js 2
€36.99
Vue.js 2 Cookbook
€36.99
Total 110.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. Going Shopping with Vue.js Chevron down icon Chevron up icon
2. Fundamentals – Installing and Using Chevron down icon Chevron up icon
3. Components – Understanding and Using Chevron down icon Chevron up icon
4. Reactivity – Binding Data to Your Application Chevron down icon Chevron up icon
5. Vuex – Managing State in Your Application Chevron down icon Chevron up icon
6. Plugins – Building Your House with Your Own Bricks Chevron down icon Chevron up icon
7. Testing – Time to Test What We Have Done So Far! Chevron down icon Chevron up icon
8. Deploying – Time to Go Live! Chevron down icon Chevron up icon
9. What Is Next? Chevron down icon Chevron up icon
A. Solutions to Exercises Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(10 Ratings)
5 star 60%
4 star 30%
3 star 0%
2 star 10%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Herbal Apr 22, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book.. I advice you to buy this book.. It's very clear and the most important thing is It's not needed component base application because this book gives you the idea.. and naturally the necessary skills to begin developing immediately.
Amazon Verified review Amazon
WiltDurkey Feb 17, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I quite liked it. Bear in mind when reading this review where I am coming from:- somewhat of a JS newbie, but have been working with it for a while using Jquery to do front-end stuff on a Django app, all with require.js and pre-es6 stuff (i.e. no Node.js or equivalent).- my frontend code was a tangled mess and really I needed to put in something cleaner. Vue fit the bill, because I could read and follow its introductory code right away, unlike React/Angular/Ember. Simple _and_ powerful is always a winning combination in my book. And it didn't seem to _require_ an SPA approach.- but... Vue, especially 2.0, is newer and has less books or online materials, so I needed something to hold my hands going from basic Hello World type examples to something more complex. All the same, I wanted basic stuff because SPA type examples wouldn't apply and I was more interested in the concepts.Pheew! Sorry for the long preamble, but it'll give you an idea of what motivates my review.First, it is quite well structured and easy to follow. You have the obligatory test applications (2 or 3 of them) and they start out using basic Vue features and then, as you go through the chapters and new Vue concepts are introduced, you see them reused, elegantly, in the apps. The apps, IMHO, strike the right balance between not being totally trivial and providing you some insight on what a real Vue-based app might look like. Vs dumping you off at the deep end with some complex code that forces you to think about the app's structure rather than what Vue is doing.Second, Vue itself mostly doesn't care that much about being used as a simple CDN-sourced library or whether it comes from a more sophisticated Node-based system. So I was following the book writing my JS as usual. But as you start looking at reusing Vue Components, then yes, Node or similar is the more natural (and less complex!) way to go. At some point, the book goes into setting up a basic Node+Webpack and points you where to download its own sample configuration. As I had node + npm already installed, I gave it a try and, lo and behold, the sample app ran perfectly. So I kind of stumbled into modern JS best practices following it along. Hey, this is about 5 pages, so no great amount of unnecessary content if you already use Webpack. But a brilliant leg up if you don't and would like to.While it builds on basic concepts, it is not dumbed down - for example there is a detailed explanation of how Vue reactivity works under the covers, starting with how you would achieve it by wrapping attributes in getters and setters.The development concepts conclude with an intro to Vuex, and how to use it to federate data and state among components. This is also important, because, as good as Vue is, it doesn't have a builtin system (events aside) to wire components together and components are compartmentalized by design. That's what Vuex is for. So you can consider Vue+Vuex as the need-to-have for real apps. Again, the concepts are well explained and easy to follow.There is some further material about testing as well. So quite a comprehensive coverage of what it covers. (Should have included 'slots' though).Conclusion: I think that, if you were coming in as an experienced Angular/React/etc... SPA-type dev, then not seeing Vue-Router/Resource and the focus on just the basics might hold you back a bit. You would certainly benefit from the way this book complements the, pretty darn good, official Vue documentation. But you might also be able to figure these things out on your own, without this book. Either way some of the more sophisticated stuff is out of scope here. So it's really a choice between are you a self-researcher or I-prefer-a-book type of guy.To be honest, while I got it at a discount, the full price is somewhat steep - but it's supply and demand stuff - few Vue books, premium price for now (c.f. the dude with the 40page/25$ book) . If you are finding your way into modern JS frontend libraries, Vue's simplicity is appealing and this book is very helpful in gently getting you up to speed.p.s. For some reason the Kindle Paperwhite version uses the smallest font ever. Whenever reading it, I am forced to switch to the largest or next-to-largest size setting, at which point it works well. But then I have to switch it back to the smaller sizes I usually use for other books. No such problem on the iPad Kindle app.
Amazon Verified review Amazon
Amazon Customer Aug 07, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Love it, the author does a good job of explaining things in a digestible way.
Amazon Verified review Amazon
Sherwin John C. Tragura Mar 12, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was looking for some help in understanding the MVC components of VUE application and this one laid out everything i need. Great book!
Amazon Verified review Amazon
amiralles Jul 08, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is awesome! The chapters are packed with code, advise, examples, tips, tricks, and a bit of humor here and there. I highly recommend this book to anyone trying to learn Vue.js.From a basic hello world to real world working app (two, actually), the author teaches you how to build, refactor, test and deploy your Vue.js apps.The code is really well written and easy to follow. I really enjoyed this book. Five starts!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela