Reader small image

You're reading from  Vue.js 2 Cookbook

Product typeBook
Published inApr 2017
Reading LevelBeginner
PublisherPackt
ISBN-139781786468093
Edition1st Edition
Languages
Right arrow
Author (1)
Andrea Passaglia
Andrea Passaglia
author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia

Right arrow

Chapter 2. Basic Vue.js Features

In this chapter, the following recipes will be covered:

  • Learning how to use computed properties
  • Filtering a list with a computed property
  • Sorting a list with a computed property
  • Formatting currencies with filters
  • Formatting dates with filters
  • Displaying and hiding an element conditionally
  • Adding styles conditionally
  • Adding some fun to your app with CSS transitions
  • Outputing raw HTML
  • Creating a form with checkboxes
  • Creating a form with radio buttons
  • Creating a form with a select element

Introduction


In this chapter, you will find all the building blocks needed to develop a fully functional, interactive, self-contained Vue application. In the first recipe, you will create computed properties that encapsulate the logic you can use to create a more semantic application; you will then explore some more text formatting with filters and the v-html directive. You will create a graphically appealing application with the help of conditional rendering and transitions. Finally, we will build some form elements such as checkboxes and radio buttons.

From now on, all recipes will be written exclusively with ES6. At the time of this writing, if you are using Chrome 9x and JSFiddle to follow along, they should work seamlessly; if you are integrating this code into a bigger project, remember to use Babel (for more information, check out the Using Babel to compile from ES6 recipe in Chapter 8, Organize + Automate + Deploy = Webpack).

Learning how to use computed properties


Computed properties are data in Vue components that depend on some calculation on other, more primitive data. When this primitive data is reactive, the computed properties are up-to-date and reactive themselves. In this context, primitive is a relative term. You can certainly build computed properties based on other computed properties.

Getting ready

Before venturing to prepare this recipe, be sure to familiarize yourself with the v-model directive and the @event notation. You can complete the React to events like clicks and keystrokes recipe in the preceding chapter if you are unsure.

How to do it...

A simple example will clarify what a computed property is:

<div id="app"> 
  <input type="text" v-model="name"/> 
  <input type="text" id="surname" value='Snow'/> 
  <button @click="saveSurname">Save Surname</button> 
  <output>{{computedFullName}}</output> 
</div> 

let surname = 'Snow' 
new Vue({ 
  el: '#app...

Filtering a list with a computed property


With the earlier version of Vue, filters were used in the v-for directives to only extract some values. They are still called filters, but they are not used in this sense anymore. They are relegated to the role of post-processing for text. To be honest, I never really understood how to use filters in Vue 1 with lists, but that won't be a problem in version 2 because the only proper way to filter a list is to use computed properties.

With this recipe, you will be able to filter your list from the simplest to-do list to the most complex bills-of-materials of a spaceship.

Getting ready

You should have some familiarity with Vue lists and know the basics of computed properties; if you don't, the Writing lists and Learning how to use computed properties recipes will get you covered.

How to do it...

To get started with this recipe, we need an example list from which to filter our favorite elements. Let's suppose we work for the ACME Research and Development...

Sorting a list with a computed property


Ordering inside a v-for with a filter is another thing that was considered for removal in Vue 1 and didn't survive in the current version.

Sorting a list with a computed property offers much more flexibility and we can implement any custom logic for ordering. In this recipe, you will create a list with some numbers within; we will sort the list using them.

Getting ready

To complete this recipe, you just require some familiarity with lists and computed properties; you can brush up on them with the Writing lists and Learning how to use computed properties recipes.

How to do it...

Let's write a list of the largest dams in the world.

First, we need an HTML table with three columns (Name, Country, Electricity):

<div id="app"> 
<table> 
  <thead> 
    <tr> 
      <th>Name</th> 
      <th>Country</th> 
      <th>Electricity</th> 
    </tr> 
  </thead> 
  <tbody> 
  </tbody> 
<...

Formatting currencies with filters


Formatting currencies in Vue 1 was somewhat limited; we will be using the excellent accounting.js library to build a much more powerful filter.

Getting ready

The basics of filtering are explored in the Formatting your text with filters recipe; where you build a basic filter ensure that you complete that, then come back here.

How to do it...

Add accounting.js to your page. Refer to http://openexchangerates.github.io/accounting.js/ for more details on how to do it. If you are using JSFiddle though, you can just add it as an external resource to the left menu. You can add a link to CDN, which is serving it, for example, https://cdn.jsdelivr.net/accounting.js/0.3.2/accounting.js.

This filter will be extremely simple:

Vue.filter('currency', function (money) { 
  return accounting.formatMoney(money) 
})

You can try it out with a one-liner in HTML:

I have {{5 | currency}} in my pocket

It will default to dollars, and it will print I have $5.00 in my pocket.

How it works...

Formatting dates with filters


Sometimes you need a slightly more powerful filter than a basic one. You have to use similar filters many times, but every time with a slight variation. Having too many filters can create confusion. This example with dates will illustrate the problem and the solution.

Getting ready

Before moving ahead, make yourself more comfortable with filters by going through the Formatting your text with filters recipe in Chapter 1Getting started with Vue.js ; if you already know filters, keep reading.

How to do it...

Let's say we are curating an interactive page to learn history. We have our Vue instance with the following JavaScript code:

new Vue({ 
  el:'#app', 
  data: { 
    bastilleStormingDate: '1789-07-14 17 h' 
  } 
})

In our data, we have a date written informally as a string in our instance data. Our HTML can contain a timeline of the French Revolution and, at some point, can contain the following:

<div id="app"> 
  The Storming of the Bastille, happened on ...

Displaying and hiding an element conditionally


Displaying and hiding an element on a web page is fundamental to some designs. You could have a popup, a set of elements that you want to display one at a time, or something that shows only when you click on a button.

In this recipe, we will use conditional display and learn about the important v-if and v-show directives.

Getting ready

Before venturing into this recipe, ensure that you know enough about computed properties or take a look at the Filtering a list with a computed property recipe.

How to do it...

Let's build a ghost that is only visible at night:

<div id="ghost"> 
  <div v-show="isNight"> 
    I'm a ghost! Boo! 
  </div> 
</div>

The v-show guarantees that the <div> ghost will be displayed only when isNight is true. For example, we may write as follows:

new Vue({ 
  el: '#ghost', 
  data: { 
    isNight: true 
  } 
})

This will make the ghost visible. To make the example more real, we can write isNight as a computed...

Adding styles conditionally


One great feature of modern web page architecture is the ability to pack tons of display logic in CSS. This means you can have a very clean and expressive HTML and still create impressive interactive pages via CSS.

Vue is particularly good at expressing relationships between HTML and CSS and allows you to encapsulate complex logic in easy-to-use functions.

In this recipe, we will explore the basics of styling with Vue.

How to do it...

We will build a text area that warns you when you are reaching the maximum allowed number of characters:

<div id="app"> 
  <textarea 
    v-model="memeText" 
    :maxlength="limit"> 
  </textarea> 
  {{memeText.length}} 
</div>

The text written inside will be bound to the memeText variable and the length of our text is written at the end via mustaches.

We want to change the background color when only 10 characters are left. For this, we have to bake a little CSS class warn:

.warn { 
  background-color: mistyrose ...

Adding some fun to your app with CSS transitions


Transitions are effects that can be applied when elements are inserted, updated, and removed from the DOM.

For this recipe, we will build a little riddle for our friends to enjoy. When they want to know the solution, it will appear with a fading transition.

Getting ready

To complete this lesson, you should already know conditional display and conditional rendering. The Displaying and hiding an element conditionally recipe will teach you how to do that.

How to do it...

Let's set up the riddle in our HTML:

<div id="app"> 
  <article> 
    They call me fruit.<br> 
    They call me fish.<br> 
    They call me insect.<br> 
    But actually I'm not one of those. 
    <div id="solution" @click="showSolution = true"> 
      I am a <span id="dragon" v-show="showSolution">Dragon</span> 
    </div> 
  </article> 
</div>

The Vue instance is initialized very easily; you just have to write the following...

Outputting raw HTML


Sometimes you need to insert HTML content, such as line breaks (<br>), in your application data. This can be easily achieved with the v-html directive.

In this recipe, we will build a thank-you note.

Getting ready

For this recipe, you don't need any special knowledge, but we will build upon some basic Vue functionalities; if you completed a recipe in this or the last chapter, you are good to go.

How to do it...

Let's say you have a friend John. You want to prepare a formatted thank-you note before receiving a gift, but you don't know what he'll be giving you yet. You prewrite three texts:

new Vue({ 
    el: '#app', 
  data: { 
    htmlTexts: [ 
    'Dear John,<br/>thank you for the <pre>Batman vs Superman</pre> DVD!', 
    'Dear John,<br/>thank you for <i>Ghostbusters 3</i>!', 
    'Dear John,<br/>thanks, <b>Gods of Egypt</b> is my new favourite!' 
    ] 
  } 
})

Consider that you were to output this variable directly...

Creating a form with checkboxes


Asking for user input is fundamental in today's web apps. Presenting the user with multiple choices makes the interface more fun to use and is necessary for structured input.

In this recipe, you will learn how to create checkboxes by building a confirmation page for your own print shop!

Getting ready

We already know how data binding works in Vue, so you are good to go. Otherwise go back to the first recipe, collect 200, and then proceed to the React to events like clicks and keystrokes recipe in Chapter 1, Getting started with Vue.js, to learn more about the v-model directive.

How to do it...

Let's suppose you have to set up a Martian printing shop with three different printers:

  • Monochrome printer
  • Plasma Color printer
  • 3D DNA Clone printer

The confirmation page will basically be just a form:

<div id="app"> 
  <form> 
    <!-- list of printers go here --> 
  </form> 
</div>

Instead of name, we will use v-model to bind our model to the view...

Creating a form with radio buttons


Radio buttons let you choose only one option among many. When the user selects a radio button, any previously selected radio button is deselected. A common example of its use is when you are creating a registration form and you choose between male and female.

Getting ready

This recipe will resemble the Creating a form with checkboxes recipe because we are using a similar technique. I suggest you to complete both the recipes to become a black belt in Vue forms.

How to do it...

First of all, we need something to choose from, so we write an array in our Vue instance:

new Vue({ 
  el: '#app', 
  data: { 
    genders: ['male', 'female', 'alien'], 
    gender: undefined 
  } 
})

We will use the variable gender (singular) to hold the value of the chosen option. From here, we can set up a form in just a few lines:

<div id="app"> 
  <form> 
    <fieldset> 
      <legend>Choose your gender</legend> 
      <label> 
        <input type...

Creating a form with a select element


Select elements or "drop-down lists" are used in a form when radio buttons won't cut it, either because there are too many choices or because they always take the same space no matter how many options.

Getting ready

I suggest you complete a recipe on data binding or forms before delving into the world of select elements. The Creating a form with radio buttons recipe will make you familiar with radio buttons, which have a function similar to select elements.

How to do it...

In this recipe, we will create a simple country selector. I will start by writing the selector without the help of Vue, just to brush up on HTML. First, create a form in which to put the select element:

<form> 
  <fieldset> 
    <legend>Choose your country</legend> 
      <!-- here goes the select element --> 
  </fieldset> 
</form>

Inside the fieldset, write the code for the select element:

<select> 
  <option>Japan</option> 
 ...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Vue.js 2 Cookbook
Published in: Apr 2017Publisher: PacktISBN-13: 9781786468093
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia