Vuejs Tutorial
Vuejs Tutorial
Vuejs Tutorial
The installation of VueJS is fairly simple, and beginners can easily understand and start
building their own user interfaces. The content is divided into various chapters that contain
related topics with simple and useful examples.
Audience
This tutorial is designed for software programmers who want to learn the basics of VueJS
and its programming concepts in a simple and easy manner. This tutorial will give the
readers enough understanding on the various functionalities of VueJS from where they can
take themselves to the next level.
Prerequisites
Before proceeding with this tutorial, readers should have a basic understanding of HTML,
CSS, and JavaScript.
Copyright &Disclaimer
Copyright 2017 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribut e or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
VueJS
Table of Contents
About the Tutorial........................................................................................................................................................... i
Audience ........................................................................................................................................................................... i
Prerequisites .................................................................................................................................................................... i
Features............................................................................................................................................................................1
3. VUEJS – INTRODUCTION............................................................................... 12
4. VUEJS – INSTANCES..................................................................................... 15
ii
VueJS
ii
1. VueJS – Overview VueJS
The installation for VueJS is very easy to start with. Any developer can easily understand
and build interactive web interfaces in a matter of time. VueJS is created by Evan You, an
ex-employee from Google. The first version of VueJS was released in Feb 2014. It recently
has clocked to 64,828 stars on GitHub, making it very popular.
Features
Following are the features available with VueJS.
Virtual DOM
VueJS makes the use of virtual DOM, which is also used by other frameworks such as
React, Ember, etc. The changes are not made to the DOM, instead a replica of the DOM is
created which is present in the form of JavaScript data structures. Whenever any changes
are to be made, they are made to the JavaScript data structures and the latter is compared
with the original data structure. The final changes are then updated to the real DOM, which
the user will see changing. This is good in terms of optimization, it is less expensive and
the changes can be made at a faster rate.
Data Binding
The data binding feature helps manipulate or assign values to HTML attributes, change the
style, assign classes with the help of binding directive called v-bind available with VueJS.
Components
Components are one of the important features of VueJS that helps create custom
elements, which can be reused in HTML.
Event Handling
v-on is the attribute added to the DOM elements to listen to the events in VueJS.
Animation/Transition
VueJS provides various ways to apply transition to HTML elements when they are
added/updated or removed from the DOM. VueJS has a built-in transition component that
needs to be wrapped around the element for transition effect. We can easily add third
party animation libraries and also add more interactivity to the interface.
1
VueJS
Computed Properties
This is one of the important features of VueJS. It helps to listen to the changes made to
the UI elements and performs the necessary calculations. There is no need of additional
coding for this.
Templates
VueJS provides HTML-based templates that bind the DOM with the Vue instance data. Vue
compiles the templates into virtual DOM Render functions. We can make use of the
template of the render functions and t o do so we have to replace the template with the
render function.
Directives
VueJS has built-in directives such as v-if, v-else, v-show, v-on, v-bind, and v-model, which
are used to perform various actions on the frontend.
Watchers
Watchers are applied to data that changes. For example, form input elements. Here, we
don’t have to add any additional events. Watcher takes care of handling any data changes
making the code simple and fast.
Routing
Navigation between pages is performed with the help of vue-router.
Lightweight
VueJS script is very lightweight and the performance is also very fast.
Vue-CLI
VueJS can be installed at the command line using the vue-cli command line interface. It
helps to build and compile the project easily using vue-cli.
VueJS and React both use virtual DOM, which makes it faster.
2
VueJS
VueJS uses html, js and css separately. It is very easy for a beginner to understand and
adopt the VueJS style. The template based approach for VueJS is very easy.
React uses jsx approach. Everything is JavaScript for ReactJS. HTML and CSS are all part
of JavaScript.
Installation Tools
React uses create react app and VueJS uses vue-cli /CDN/npm. Both are very easy to
use and the project is set up with all the basic requirements. React needs webpack for the
build, whereas VueJS does not. We can start with VueJS coding anywhere in jsfiddle or
codepen using the cdn library.
Popularity
React is popular than VueJS. The job opportunity with React is more than VueJS. There is
a big name behind React i.e. Facebook which makes it more popular. Since, React uses
the core concept of JavaScript, it uses the best practice of JavaScript. One who works with
React will definitely be a very good with all the JavaScript concepts.
VueJS is a developing framework. Presently, the job opportunities with VueJS are less in
comparison to React. According to a survey, many people are adapting to VueJS, which
can make it more popular in comparison to React and Angular. There is a good communit y
working on the different features of VueJS. The vue-router is maintained by this
community with regular updates.
VueJS has taken the good parts from Angular and React and has built a powerful library.
VueJS is much faster in comparison to React/Angular because of its light weight library.
Complexity
Vuejs is very easy to learn and start with. As discussed earlier, a beginner can take the
CDN library of VueJS and get started in codepen and jsfiddle.
For Angular, we need to go through a series of steps for installation and it is little difficult
for beginners to get started with Angular. It uses TypeScript for coding which is difficult
for people coming from core JavaScript background. However, it is easier to learn for users
belonging to Java and C# background.
Performance
To decide the performance, it is up to the users. VueJS file size is much lighter than
Angular. A comparison of the framework performance is provided in the following link
http://stefankrause.net/js-frameworks-benchmark4/webdriver-ts/table.html
3
VueJS
Popularity
At present, Angular is more popular than VueJS. A lot of organizations use Angular, making
it very popular. Job opportunities are also more for candidates experienced in Angular.
However, VueJS is taking up the place in the market and can be considered as a good
competitor for Angular and React.
Dependencies
Angular provides a lot of built-in features. We have to import the required modules and
get started with it, for example, @angular/animations, @angular/form.
VueJS does not have all the built-in features as Angular and needs to depend on third
party libraries to work on it.
Flexibility
VueJS can be easily merged with any other big project without any issues. Angular will not
be that easy to start working with any other existing project.
Backward Compatibility
We had AngularJS, Angular2 and now Angular4. AngularJS and Angular2 have vast
difference. Project application developed in AngularJS cannot be converted to Angular2
because of the core differences.
The recent version of VueJS is 2.0 and it is good with backward compatibility. It provides
good documentation, which is very easy to understand.
Typescript
Angular uses TypeScript for its coding. Users need to have knowledge of Typescript to get
started with Angular. However, we can start with VueJS coding anywhere in jsfiddle or
codepen using the cdn library. We can work with standard JavaScript, which is very easy
to start with.
VueJS has also a command line tool vue-cli to start and build projects.
They both have features such as router, template, and components which makes them
very rich as the UI framework.
Performance
VueJS has better performance in comparison to Ember. Ember has added a glimme r
rendering engine with the aim of improving the re-render performance, which is a similar
concept as VueJS and React using virtual DOM. However, VueJS has a better performanc e
when compared to Ember.
4
VueJS
On the other hand, VueJS has started gaining popularity with the Vue team providing
regular updates.
Polymer uses web component features and requires polyfills for browsers, which does not
support these features. VueJS does not have such dependencies and works fine in all
browsers from IE9+.
5
2. VueJS – Environment Setup VueJS
There are many ways to install VueJS. Some of the ways on how to carry out the
installation are discussed ahead.
<html>
<head>
<script type="text/javascript" src="vue.min.js"></script>
</head>
<body>
</body>
</html>
6
VueJS
Using CDN
We can also start using VueJS file from the CDN library. The link https://unpkg.com/vue
will give the latest version of VueJS. VueJS is also available on jsDelivr
(https://cdn.jsdelivr.net/npm/vue/dist/vue.js) and cdnjs
(https://cdnjs.cloudflare.com/ajax/libs/vue/2.4. 0/vue.js).
We can host the files at our end, if required and get started with VueJS development.
Using NPM
For large scale applications with VueJS, it is recommended to install using the npm
package. It comes with Browserify and Webpack along with other necessary tools, which
help with the development. Following is the command to install using npm.
7
VueJS
Once done, it shows the CLI version for VueJS. It takes a few minutes for the installation.
+ vue-cli@2.8.2
added 965 packages in 355.414s
cd myproject
npm install
8
VueJS
Once we execute npm run dev, it starts the server and provides the url for display to be
seen in the browser which is as shown in the following screenshot.
9
VueJS
10
VueJS
11
3. VueJS – Introduction VueJS
Vue is a JavaScript framework for building user interfaces. Its core part is focused mainly
on the view layer and it is very easy to understand. The version of Vue that we are going
to use in this tutorial is 2.0.
As Vue is basically built for frontend development, we are going to deal with lot of HTML,
JavaScript and CSS files in the upcoming chapters. To understand the details, let us start
with a simple example.
Example
<html>
<head>
<title>VueJs Introduction</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="intro" style="text-align:center;">
<h1>{{ message }}</h1>
</div>
<script type="text/javascript">
var vue_det = new Vue({
el: '#intro',
data: {
message: 'My first VueJS Task'
}
});
</script>
</body>
</html>
12
VueJS
Output
This is the first app we have created using VueJS. As seen in the above code, we have
included vue.js at the start of the .html file.
There is a div which is added in the body that prints “My first VueJS Task” in the browser.
We have also added a message in a interpolation, i.e. {{}}. This interacts with VueJS and
prints the data in the browser. To get the value of the message in the DOM, we are creating
an instance of vuejs as follows:
In the above code snippet, we are calling Vue instance, which takes the id of the DOM
element i.e. e1:’#intro’, it is the id of the div. There is data with the message which is
assigned the value ‘My first VueJS Task’. VueJS interacts with DOM and changes the
value in the DOM {{message}} with ’My first VueJS Task’.
13
VueJS
If we happen to change the value of the message in the console, the same will be reflected
in the browser. For example:
Console Details
In the above console, we have printed the vue_det object , which is an instance of Vue.
We are updating the message with “VueJs is interesting” and the same is changed in
the browser immediately as seen in the above screenshot.
This is just a basic example showing the linking of VueJS with DOM, and how we can
manipulate it. In the next few chapters, we will learn about directives, components,
conditional loops, etc.
14
4. VueJS – Instances VueJS
To start with VueJS, we need to c reate the instance of Vue, which is called the root Vue
Instance.
Syntax
var app = new Vue({
// options
})
Let us look at an example to understand what needs to be part of the Vue constructor.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<h1>{{mydetails()}}</h1>
</div>
<script type="text/javascript" src="js/vue_instance.js"></script>
</body>
</html>
15
VueJS
vue_instance.js
For Vue, there is a parameter called e1. It takes the id of the DOM element. In the above
example, we have the id #vue_det. It is the id of the div element , which is present in
.html.
<div id="vue_det"></div>
Now, whatever we are going to do will affect the div element and nothing outside it.
Next, we have defined the data object. It has value firstname, lastname, and address.
<div id="vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
</div>
The Firstname : {{firstname}} value will be replaced inside the interpolation, i.e. {{}}
with the value assigned in the data object , i.e. Ria. The same goes for last name.
16
VueJS
Next, we have methods where we have defined a function mydetails and a returning value.
It is assigned inside the div as
<h1>{{mydetails()}}</h1>
Hence, inside {{} } the function mydetails is called. The value returned in the Vue instance
will be printed inside {{}}. Check the output for reference.
Output
Now, we need to pass options to the Vue constructor which is mainly data, template,
element to mount on, methods, callbacks, etc.
#data: This type of data can be an object or a function. Vue converts its properties to
getters/setters to make it reactive.
Example
<html>
<head>
<title>VueJs Introduction</title>
17
VueJS
<body>
<script type="text/javascript">
var _obj = { fname: "Raj", lname: "Singh"}
// direct instance creation
var vm = new Vue({
data: _obj
});
console.log(vm.fname);
console.log(vm.$data);
console.log(vm.$data.fname);
</script>
</body>
</html>
18
VueJS
Output
19
VueJS
If there is a component, the data object has to be referred from a function as shown in
the following code.
<html>
<head>
<title>VueJs Introduction</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<script type="text/javascript">
var _obj = { fname: "Raj", lname: "Singh"};
// direct instance creation
var vm = new Vue({
data: _obj
});
console.log(vm.fname);
console.log(vm.$data);
console.log(vm.$data.fname);
// must use function when in Vue.extend()
var Component = Vue.extend({
data: function () {
return _obj
}
});
var myComponentInstance = new Component();
console.log(myComponentInsta nce.lname);
console.log(myComponentInstance.$data);
</script>
</body>
</html>
20
VueJS
In case of a component, the data is a function, which is used with Vue.extend as shown
above. The data is a function. For example,
data: function () {
return _obj
}
To refer to the data from the component , we need to create an instance of it. For example,
To fetch the details from the data, we need to do the same as we did with the parent
component above. For example,
console.log(myComponentInstance.lname);
console.log(myComponentInstance.$data);
21
VueJS
Props: Type for props is an array of string or object. It takes an array-based or object-
based syntax. They are said to be attributes used to accept data from the parent
component.
Example 1
Vue.component('props-demo-simple', {
props: ['size', 'myMessage']
})
Example 2
Vue.component('props-demo-advanced', {
props: {
// just type check
height: Number,
// type check plus other validations
age: {
type: Number,
default: 0,
required: true,
validator: function (value) {
return value >= 0
}
}
}
})
Type: array of string. For example, { [key: string]: any }. It needs to be passed during
the creation of Vue instance.
22
VueJS
Example
Example
<html>
<head>
<title>VueJs Introduction</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<script type="text/javascript">
var vm = new Vue({
data: { a: 2 },
computed: {
// get only, just need a function
aSum: function () {
return this.a + 2;
},
// both get and set
aSquare: {
get: function () {
return this.a*this.a;
},
set: function (v) {
this.a = v*2;
23
VueJS
}
}
}
})
console.log(vm.aSquare); // -> 4
vm.aSquare = 3;
console.log(vm.a); // -> 6
console.log(vm.aSum); // -> 8
</script>
</body>
</html>
Function aSum just returns this.a+2. Function aSquare again two functions get and set.
Variable vm is an instance of Vue and it calls aSquare and aSum. Also vm.aSquare = 3
calls the set function from aSquare and vm.aSquare calls the get function. We can check
the output in the browser which looks like the following screenshot.
Methods: Methods are to be included with the Vue instance as shown in the following
code. We can access the function using the Vue object.
<html>
<head>
<title>VueJs Introduction</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<script type="text/javascript">
var vm = new Vue({
data: { a: 5 },
methods: {
24
VueJS
asquare: function () {
this.a *= this.a;
}
}
})
vm.asquare();
console.log(vm.a); // 25
</script>
</body>
</html>
Methods are part of the Vue constructor. Let us make a call to the method using the Vue
object vm.asquare (), the value of the property a is updated in the asquare function.
The value of a is changed from 1 to 25, and the same is seen reflected in the following
browser console.
25
5. VueJS – Template VueJS
We have learnt in the earlier chapters, how to get an output in the form of text content
on the screen. In this chapter, we will learn how to get an output in the form of HTML
template on the screen.
To understand this, let us consider an example and see the output in the browser.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<div>{{htmlcontent}}</div>
</div>
<script type="text/javascript" src="js/vue_template.js"></script>
</body>
</html>
vue_template.js
}
})
26
VueJS
Now, suppose we want to show the html content on the page. If we happen to use it with
interpolation, i.e. with double curly brackets, this is what we will get in the browser.
If we see the html content is displayed the same way we have given in the variable
htmlcontent, this is not what we want, we want it to be displayed in a proper HTML content
on the browser.
For this, we will have to use v-html directive. The moment we assign v-html directive to
the html element, VueJS knows that it has to output it as HTML content. Let’s add v-html
directive in the .html file and see the difference.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<div v-html="htmlcontent"></div>
</div>
<script type="text/javascript" src="js/vue_template.js"></script>
</body>
</html>
27
VueJS
Now, we don’t need the double curly brackets to show the HTML content, instead we have
used v-html=”htmlcontent” where htmlcontent is defined inside the js file as follows:
If we inspect the browser, we will see the content is added in the same way as it is defined
in the .js file to the variable htmlcontent : "<div><h1>Vue Js
Template</h1></div>".
28
VueJS
We have seen how to add HTML template to the DOM. Now, we will see how to add
attributes to the exiting HTML elements.
Consider, we have an image tag in the HTML file and we want to assign src , which is a
part of Vue.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<div v-html="htmlcontent"></div>
<img src="" width="300" height="250" />
</div>
<script type="text/javascript" src="js/vue_template1.js"></script>
</body>
</html>
29
VueJS
Look at the img tag above, the src is blank. We need to add the src to it from vue js. Let
us take a look at how to do it. We will store the img src in the data object in the .js file as
follows:
If we assign the src as follows, the output in the browser will be as shown in the following
screenshot.
30
VueJS
We get a broken image. To assign any attribute to HMTL tag, we need to use v-bind
directive. Let’s add the src to the image with v-bind directive.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="vue_det">
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
31
VueJS
<div v-html="htmlcontent"></div>
<img v-bind:src="imgsrc" width="300" height="250" />
</div>
<script type="text/javascript" src="js/vue_template1.js"></script>
</body>
</html>
We need to prefix the src with v-bind:src=”imgsrc” and the name of the variable with
src.
32
VueJS
Let us inspect and check how the src looks like with v-bind.
As seen in the above screenshot, the src is assigned without any vuejs properties to it.
33
6. VueJS – Components VueJS
Vue Components are one of the important features of VueJS that creates custom
elements, which can be reused in HTML.
Let’s work with an example and create a component, that will give a better understanding
on how components work with VueJS.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="component_test">
<testcomponent></testcomponent>
</div>
<div id="component_test1">
<testcomponent></testcomponent>
</div>
<script type="text/javascript" src="js/vue_component.js"></script>
</body>
</html>
vue_component.js
Vue.component('testcomponent',{
template : '<div><h1>This is coming from component</h1></div>'
});
34
VueJS
In the .html file, we have created two div with id component_test and
component_test1. In the .js files shown above, two Vue instances are created with the
div ids. We have created a common component to be used with both the view instances.
Vue.component('nameofthecomponent',{ // options});
Once a component is created, the name of the component becomes the custom element
and the same can be used in the Vue instance element created, i.e. inside the div with ids
component_test and component_test1.
In the .js file, we have used a test component as the name of the component and the
same name is used as the custom element inside the divs.
Example
<div id="component_test">
<testcomponent></testcomponent>
</div>
<div id="component_test1">
<testcomponent></testcomponent>
</div>
In the component created in the .js file, we have added a template to which we have
assigned a HTML code. This is a way of registering a global component, which can be
made a part of any vue instance as shown in the following script.
Vue.component('testcomponent',{
template : '<div><h1>This is coming from component</h1></div>'
});
35
VueJS
We have also directly made the components a part of vue instance as shown in the
following script.
36
VueJS
This is called local registration and the components will be a part of only the vue instance
created.
So far, we have seen the basic component with the basic options. Now, let’s add some
more options such as data and methods to it. Just as Vue instance has data and methods,
component also shares the same. Hence, we will extend the code, which we have already
seen with data and methods.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="component_test">
<testcomponent></testcom ponent>
</div>
<div id="component_test1">
<testcomponent></testcomponent>
</div>
<script type="text/javascript" src="js/vue_component.js"></script>
</body>
</html>
vue_component.js
Vue.component('testcomponent',{
template : '<div v-on:mouseover="changename()" v -
on:mouseout="originalname();"><h1>Custom Component created by <span
id="name">{{name}}</span></h1></div>',
data: function() {
return {
name : "Ria"
}
},
37
VueJS
methods:{
changename : function() {
this.name = "Ben";
},
originalname: function() {
this.name = "Ria";
}
}
});
In the .js file above, we have added data that is a function, which returns an object. The
object has a name property, which is assigned the value ‘Ria’. This is used in the following
template.
In spite of having data as a function in components, we can use its properties the same
way as we use with direct Vue instance. Also, there are two methods added, changename
and originalname. In changename, we are changing the name property, and in
originalname we are resetting it back to the original name.
We have also added two events on the div, mouseover and mouseout. The details of the
events will be discussed in the Events chapter. So for now, mouseover calls changename
method and mouseout calls originalname method.
38
VueJS
As seen in the above browser, it displays the name assigned in the data property, which
is the same name. We have also assigned a mouseover event on the div and also a
mouseout. Let’s see what happens when we mouseover and mouseout.
On mouseover, we see the name of the first component is changed to Ben, however, the
second one remains as it is. This is because the data component is a function and it returns
an object. Thus, when it is changed in one place, the same is not overwritten in other
cases.
39
VueJS
Dynamic Components
Dynamic components are created using the keyword <component></component> and
it is bound using a property as shown in the following example.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<component v-bind:is="view"></component>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
view: 'component1'
},
components: {
'component1': {
template: '<div><span style="font-
size:25;color:red;">Dynamic Component</span></div>'
}
}
});
</script>
</body>
</html>
40
VueJS
Output
<component v-bind:is="view"></component>
It has v-bind:is=”view”, and a value view is assigned to it. View is defined in the Vue
instance as follows.
41
7. VueJS – Computed Properties VueJS
We have already seen methods for Vue instance and for components. Computed properties
are like methods but with some difference in comparison to methods, which we will discuss
in this chapter.
At the end of this chapter, we will be able to make a decision on when to use methods and
when to use computed properties.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="computed_props">
FirstName : <input type="text" v-model="firstname" /> <br/><br/>
LastName : <input type="text" v-model="lastname"/> <br/><br/>
<h1>My name is {{firstname}} {{lastname}}</h1>
<h1>Using computed method : {{getfullname}}</h1>
</div>
<script type="text/javascript" src="js/vue_computedprops.js"></script>
</body>
</html>
vue_computeprops.js
42
VueJS
birthyear : ""
},
computed :{
getfullname : function(){
return this.firstname +" "+ this.lastname;
}
}
})
Here, we have created .html file with firstname and lastname. Firstname and Lastname
is a textbox which are bound using properties firstname and lastname.
We are calling the computed method getfullname, which returns the firstname and the
lastname entered.
computed :{
getfullname : function(){
return this.firstname +" "+ this.lastname;
}
}
When we type in the textbox the same is returned by the funct ion, when the properties
firstname or lastname is changed. Thus, with the help of computed we don’t have to do
anything specific , such as remembering to call a function. With computed it gets called by
itself, as the properties used inside changes, i.e. firstname and lastname.
The same is displayed in the following browser. Type in the textbox and the same will get
updated using the computed function.
43
VueJS
Now, let’s try to understand the difference between a method and a computed property.
Both are objects. There are functions defined inside, which returns a value.
In case of method, we call it as a function, and for computed as a property. Using the
following example, let us understand the difference between method and computed
property.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="computed_props">
<h1 style="background-color:gray;">Random No from computed property:
{{getrandomno}}</h1>
<h1>Random No from method: {{getrandomno1()}}</h1>
<h1>Random No from method : {{getrandomno1()}}</h1>
<h1 style="background-color:gray;">Random No from computed
property: {{getrandomno}}</h1>
<h1 style="background-color:gray;">Random No from computed
property: {{getrandomno}}</h1>
<h1 style="background-color:gray;">Random No from computed
44
VueJS
property: {{getrandomno}}</h1>
<h1>Random No from method: {{getrandomno1()}}</h1>
<h1>Random No from method: {{getrandomno1()}}</h1>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#computed_props',
data: {
name : "helloworld"
},
methods: {
getrandomno1 : function() {
return Math.random();
}
},
computed :{
getrandomno : function(){
return Math.random();
}
}
});
</script>
</body>
</html>
In the above code, we have created a method called getrandomno1 and a computed
property with a function getrandomno. Both are giving back random numbers using
Math.random().
It is displayed in the browser as shown below. The method and computed property are
called many times to show the difference.
45
VueJS
If we look at the values above, we will see that the random numbers returned from the
computed property remains the same irrespective of the number of times it is called. This
means everytime it is called, the last value is updated for all. Whereas for a method, it’s
a function, hence, everytime it is called it returns a different value.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="computed_props">
<input type="text" v-model="fullname" />
<h1>{{firstName}}</h1>
<h1>{{lastName}}</h1>
46
VueJS
</div>
<script type="text/javascript">
},
computed :{
fullname : {
get : function() {
return this.firstName+" "+this.lastName;
}
}
}
});
</script>
</body>
</html>
We have defined one input box which is bound to fullname, which is a computed property.
It returns a function called get, which gives the fullname, i.e. the first name and the
lastname. Also, we have displayed the firstname and lastname as:
<h1>{{firstName}}</h1>
<h1>{{lastName}}</h1>
47
VueJS
Now, if we change the name in the textbox, we will see the same is not reflected in the
name displayed in the following screenshot.
48
VueJS
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="computed_props">
<input type="text" v-model="fullname" />
<h1>{{firstName}}</h1>
<h1>{{lastName}}</h1>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#computed_props',
data: {
firstName : "Terry",
lastName : "Ben"
},
methods: {
},
computed :{
fullname : {
get : function() {
return this.firstName+" "+this.lastName;
},
set : function(name) {
var fname = name.split(" ");
this.firstName = fname[0];
this.lastName = fname[1]
}
}
}
49
VueJS
});
</script>
</body>
</html>
computed :{
fullname : {
get : function() {
return this.firstName+" "+this.lastName;
},
set : function(name) {
var fname = name.split(" ");
this.firstName = fname[0];
this.lastName = fname[1]
}
}
}
It has the name as the parameter, which is nothing but the fullname in the textbox. Later,
it is split on space and the firstname and the lastname is updated. Now, when we run the
code and edit the textbox, the same thing will be displayed in the browser. The firstname
and the lastname will be updated because of the set function. The get function returns the
firstname and lastname, while the set function updates it, if anything is edited.
50
VueJS
Now, whatever is typed in the textbox matches with what is displayed as seen in the above
screenshot.
51
8. VueJS - Watch Property VueJS
In this chapter, we will learn about the Watch property. Using an example, we will see we
can use the Watch property in VueJS.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="computed_props">
Kilometers : <input type="text" v-model="kilometers">
Meters : <input type="text" v-model="meters">
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#computed_props',
data: {
kilometers : 0,
meters:0
},
methods: {
},
computed :{
},
watch : {
kilometers:function(val) {
this.kilometers = val;
this.meters = val * 1000;
},
meters : function (val) {
52
VueJS
In the above code, we have created two textboxes, one with kilometers and another with
meters. In data property, the kilometers and meters are initialized to 0. There is a watch
object created with two functions kilometers and meters. In both the functions, the
conversion from kilometers to meters and from meters to kilometers is done.
As we enter values inside any of the texboxes, whichever is changed, Watch takes care of
updating both the textboxes. We do not have to specially assign any events and wait for
it to change and do the extra work of validating. Watch takes care of updating the
textboxes with the calculation done in the respective functions.
Let’s enter some values in the kilometers textbox and see it changing in the meters textbox
and vice-versa.
53
VueJS
Let’s now enter in meters textbox and see it changing in the kilometers textbox. This is
the display seen in the browser.
54
9. VueJS - Binding VueJS
In this chapter will learn how to manipulate or assign values to HTML attributes, change
the style, and assign classes with the help of binding directive called v-bind available with
VueJS.
Let’s consider an example to understand why we need and when to use v-bind directive
for data binding.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
{{title}}<br/>
<a href="hreflink" target="_blank"> Click Me </a> <br/>
<a href="{{hreflink}}" target="_blank">Click Me </a> <br/>
<a v-bind:href="hreflink" target="_blank">Click Me </a> <br/>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
title : "DATA BINDING",
hreflink : "http://www.google.com"
}
});
</script>
</body>
</html>
55
VueJS
In above example, we have displayed a title variable and three anchor links. We have also
assigned a value to the href from the data object.
Now, if we check the output in the browser and inspect , we will see the first two anchor
links do not have the href correctly as shown in the following screenshot .
The first clickme shows the href as hreflink, and the second one shows it in {{hreflink}},
while the last one displays the correct url as we require.
Hence, to assign values to HTML attributes, we need to bind it with the directive v-bind as
follows.
If we see the inspect element in the browser, the anchor tag does not show the v-bind
attribute, however, it displays the plain HTML. None of the VueJS properties are seen when
we inpsect the DOM.
56
VueJS
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.active {
background: red;
}
</style>
<div id="classbinding">
<div v-bind:class="{active:isactive}"><b>{{title}}</b></div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#classbinding',
data: {
title : "CLASS BINDING",
isactive : true
}
});
</script>
</body>
</html>
Here, isactive is a variable which is based on true or false. It will apply the class active
to the div. In the data object, we have assigned the isactive variable as true. There is a
class defined in the style .active with the background color as red.
57
VueJS
If the variable isactive is true, the color will be applied otherwise not. Following will be the
output in the browser.
In above display, we can see the background color is red. The class=”active” is applied to
the div.
Now, let’s change the value of the variable to false and see the output. The variable isactive
is changed to false as shown in the following code.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.active {
background: red;
}
</style>
<div id="classbinding">
<div v-bind:class="{active:isactive}"><b>{{title}}</b></div>
</div>
<script type="text/javascript">
58
VueJS
data: {
title : "CLASS BINDING",
isactive : false
}
});
</script>
</body>
</html>
In the above display, we can see the active class is not applied to the div.
We can also assign multiple classes to the HTML tags using v-bind attribute.
59
VueJS
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.info {
color: #00529B;
background-color: #BDE5F8;
}
div {
margin: 10px 0;
padding: 12px;
}
.active {
color: #4F8A10;
background-color: #DFF2BF;
}
.displayError{
color: #D8000C;
background-color: #FFBABA;
}
</style>
<div id="classbinding">
<div class="info" v-bind:class="{ active: isActive,
'displayError': hasError }">
{{title}}
</div>
</div>
<script type="text/javascript">
60
VueJS
data: {
title : "This is class binding example",
isActive : false,
hasError : false
}
});
</script>
</body>
</html>
For the div in the above code, we have applied a normal class, example class=”info”. Based
on isActive and hasError variable, the other classes will get applied t o the div.
Output
This is a normal class applied. Both the variables are false right now. Let’s make isActive
variable to true and see the output .
61
VueJS
In the above display, in the DOM we can see two classes assigned to the div, info and
active. Let’s make hasError variable true and isActive as false.
Now, when we see in the above display, info and displayError class is applied to the div.
This is how we can apply multiple classes based on conditions.
We can also pass c lass as an array. Let us take an example to understand this.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.info {
color: #00529B;
background-color: #BDE5F8;
62
VueJS
}
div {
margin: 10px 0;
padding: 12px;
font-size : 25px;
}
.active {
color: #4F8A10;
background-color: #DFF2BF;
}
.displayError{
color: #D8000C;
background-color: #FFBABA;
}
</style>
<div id="classbinding">
<div v-bind:class="[infoclass, errorclass]">{{title}}</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#classbinding',
data: {
title : "This is class binding example",
infoclass : 'info',
errorclass : 'displayError'
}
});
</script>
</body>
</html>
63
VueJS
Output
As we can see above, both classes get applied to the div. Let’s use a variable and based
on the value of the variable, assign the class.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.info {
color: #00529B;
background-color: #BDE5F8;
}
div {
margin: 10px 0;
padding: 12px;
font-size : 25px;
}
.active {
color: #4F8A10;
background-color: #DFF2BF;
}
.displayError{
64
VueJS
color: #D8000C;
background-color: #FFBABA;
}
</style>
<div id="classbinding">
<div v-bind:class="[isActive ? infoclass : '', haserror ?
errorclass : '']">{{title}}</div>
65
VueJS
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#classbinding',
data: {
title : "This is class binding example",
infoclass : 'info',
errorclass : 'displayError',
isActive : true,
haserror : false
}
});
</script>
</body>
</html>
We have used two variables isActive and haserror and the same is used for the div while
class binding as shown in the following div tag.
If isActive is true, then infoclass will be assigned to it. The same goes for haserror, if it is
true, then only errorClass will be applied to it.
Now, let us make haserror variable as true and isActive variable as false.
66
VueJS
We will now add v-bind for classes in the components. In the following example, we have
added a class to the component template and also to the component.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.info {
color: #00529B;
background-color: #BDE5F8;
}
div {
margin: 10px 0;
padding: 12px;
font-size : 25px;
}
.active {
color: #4F8A10;
background-color: #DFF2BF;
}
67
VueJS
.displayError{
color: #D8000C;
background-color: #FFBABA;
}
</style>
<div id="classbinding">
<new_component class="active"></new_component>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#classbinding',
data: {
title : "This is class binding example",
infoclass : 'info',
errorclass : 'displayError',
isActive : false,
haserror : true
},
components:{
'new_component' : {
template : '<div class="info">Class Binding for
component</div>'
}
}
});
</script>
</body>
</html>
Following is the output in the browser. It applies both the classes to final div.
68
VueJS
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.info {
color: #00529B;
background-color: #BDE5F8;
}
div {
margin: 10px 0;
padding: 12px;
font-size : 25px;
}
.active {
color: #4F8A10;
background-color: #DFF2BF;
}
.displayError{
color: #D8000C;
background-color: #FFBABA;
}
69
VueJS
</style>
<div id="classbinding">
<new_component v-bind:class="{active:isActive}"></new_component>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#classbinding',
data: {
title : "This is class binding example",
infoclass : 'info',
errorclass : 'displayError',
isActive : false,
haserror : true
},
components:{
'new_component' : {
template : '<div class="info">Class Binding for
component</div>'
}
}
});
</script>
</body>
</html>
Since the variable is false, the active class is not applied and the info class is applied as
shown in the following screenshot.
70
VueJS
Object Syntax
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<div v-bind:style="{ color: activeColor, fontSize: fontSize +
'px' }">{{title}}</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
title : "Inline style Binding",
activeColor: 'red',
fontSize :'30'
}
});
</script>
</body>
</html>
Output
71
VueJS
In the above example, for the div, the style is applied and the data is fetched from the
data object.
data: {
title : "Inline style Binding",
activeColor: 'red',
fontSize :'30'
}
We can also do the same thing by assigning all the values to a variable and then assigning
the variable to the div.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<div v-bind:style="styleobj">{{title}}</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
title : "Inline style Binding",
styleobj : {
color: 'red',
fontSize :'40px'
}
}
});
</script>
72
VueJS
</body>
</html>
The color and the fontSize is assigned to the object called styleobj and the same is
assigned to the div.
<div v-bind:style="styleobj">{{title}}</div>
Output
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<h3>TEXTBOX</h3>
<input v-model="name" placeholder="Enter Name" />
<h3>Name entered is : {{name}}</h3>
<hr/>
<h3>Textarea</h3>
<textarea v-model="textmessage" placeholder="Add
Details"></textarea>
<h1><p>{{textmessage}}</p></h1>
73
VueJS
<hr/>
<h3>Checkbox</h3>
<input type="checkbox" id="checkbox" v-model="checked"> {{checked}}
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
name:'',
textmessage:'',
checked : false
}
});
</script>
</body>
</html>
Whatever we type in the texbox is displayed below. v-model is assigned the value name
and the name is displayed in {{name}}, which displays whatever is typed in the textbox.
Output
Let’s checkout out some more examples and how to use it.
74
VueJS
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<h3>Radio</h3>
<input type="radio" id="black" value="Black" v -model="picked">Black
<input type="radio" id="white" value="White" v -model="picked">White
<h3>Radio element clicked : {{picked}} </h3>
<hr/>
<h3>Select</h3>
<select v-model="languages">
<option disabled value="">Please select one</option>
<option>Java</option>
<option>Javascript</option>
<option>Php</option>
<option>C</option>
<option>C++</option>
</select>
<h3>Languages Selected is : {{ languages }}</h3>
<hr/>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
picked : 'White',
languages : "Java"
}
});
75
VueJS
</script>
</body>
</html>
Output
Modifiers
We have used three modifiers in the example - trim, number, and lazy.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<span style="font-size:25px;">Enter Age:</span> <input v-
model.number="age" type="number">
76
VueJS
<br/>
<span style="font-size:25px;">Enter Message:</span> <input v -
model.lazy="msg">
<h3>Display Message : {{msg}}</h3>
<br/>
<span style="font-size:25px;">Enter Message : </span><input v-
model.trim="message">
<h3>Display Message : {{message}}</h3>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
age : 0,
msg: '',
message : ''
}
});
</script>
</body>
</html>
77
VueJS
Output
Number modifier allows to only enter numbers. It will not take any other input besides
numbers.
Lazy modifier will display the content present in the textbox once it is fully entered and
the user leaves the textbox.
Trim modifier will remove any spaces entered at the start and at the end.
78
10. VueJS - Events VueJS
v-on is the attribute added to the DOM elements to listen to the events in VueJS.
Click Event
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<button v-on:click="displaynumbers">Click ME</button>
<h2> Add Number 100 + 200 = {{total}}</h2>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
num1: 100,
num2 : 200,
total : ''
},
methods : {
displaynumbers : function(event) {
console.log(event);
return this.total = this.num1+ this.num2;
}
},
});
</script>
79
VueJS
</body>
</html>
Output
The following code is used to assign a click event for the DOM element.
There is a shorthand for v-on, which means we can also call the event as follows:
80
VueJS
On the click of the button, it will call the method ‘displaynumbers ’, which takes in the
event and we have consoled the same in the browser as shown above.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<div v-bind:style="styleobj" v-on:mouseover="changebgcolor" v -
on:mouseout="originalcolor"></div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
num1: 100,
num2 : 200,
total : '',
styleobj : {
width:"100px",
height:"100px",
backgroundColor:"red"
}
},
methods : {
changebgcolor : function() {
this.styleobj.backgroundColor = "green";
},
originalcolor : function() {
this.styleobj.backgroundColor = "red";
81
VueJS
}
},
});
</script>
</body>
</html>
In the above example, we have created a div with width and height as 100px. It has been
given a background color red. On mouseover, we are changing the color to green, and on
mouseout we are changing the color back to red.
Hence, during mouseover, a method is called changebgcolor and once we move the
mouse out of the div, a method is called originalcolor.
Two events - mouseover and mouseout - is assigned to the div as shown above. We have
created a styleobj variable and given the required style to be assigned to the div . The
same variable is binded to the div using v-bind:style=”styleobj”
In changebgcolor, we are changing the color to green using the following code.
changebgcolor : function() {
this.styleobj.backgroundColor = "green";
}
Similarly, the following code is used to change it back to the original color.
originalcolor : function() {
this.styleobj.backgroundColor = "red";
}
82
VueJS
When we mouseover, the color will change to green as shown in the following screenshot.
83
VueJS
Event Modifiers
Vue has event modifiers available on v-on attribute. Following are the modifiers available:
.once
Allows the event to execute only once.
Syntax
We need to add dot operator while calling the modifiers as shown in the syntax above. Let
us use it in an example and understand the working of the once modifier.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<button v-on:click.once="buttonclickedonce" v-
bind:style="styleobj">Click Once</button>
Output:{{clicknum}}
<br/><br/>
<button v-on:click="buttonclicked" v -bind:style="styleobj">Click
Me</button>
Output:{{clicknum1}}
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
clicknum : 0,
clicknum1 :0,
styleobj: {
backgroundColor: '#2196F3!important',
cursor: 'pointer',
84
VueJS
Output
85
VueJS
In the above example, we have created two butttons. The button with Click Once label has
added the once modifier and the other button is without any modifier. This is the way the
buttons are defined.
The first button calls the method “buttonclickedonce” and the second button calls the
method “buttonclicked”.
buttonclickedonce : function() {
this.clicknum++;
},
buttonclicked : function() {
this.clicknum1++;
}
There are two variables defined in the clicknum and clicknum1. Both are increment ed
when the button is clicked. Both the variables are initialized to 0 and the display is seen
in the output above.
On the click of the first button, the variable clicknum increments by 1. On the second click,
the number is not incremented as the modifier prevents it from executing or performing
any action item assigned on the click of the button.
On the click of the second button, the same action is carried out, i.e. the variable is
incremented. On every click, the value is incremented and displayed.
86
VueJS
.prevent
Syntax
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<a href="http://www.google.com" v-on:click="clickme"
target="_blank" v-bind:style="styleobj">Click Me</a>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
clicknum : 0,
clicknum1 :0,
styleobj: {
color: '#4CAF50',
marginLeft: '20px',
fontSize: '30px'
}
},
methods : {
clickme : function() {
alert("Anchor tag is clicked");
}
}
});
</script>
</body>
87
VueJS
</html>
Output
If we click the clickme link, it will send an alert as “Anchor tag is clicked” and it will open
the link http://www.google.com in a new tab as shown in the following screenshots.
88
VueJS
Now this works as a normal way, i.e. the link opens up as we want. In case we don’t want
the link to open up, we need to add a modifier ‘prevent’ to the event as shown in the
following code.
Once added, if we click on the button, it will send an alert message and will not open the
link anymore. The prevent modifier prevents the link from opening and only executes the
method assigned to the tag.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<a href="http://www.google.com" v-on:click.prevent="clickme"
target="_blank" v-bind:style="styleobj">Click Me</a>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
clicknum : 0,
clicknum1 :0,
styleobj: {
color: '#4CAF50',
marginLeft: '20px',
fontSize: '30px'
}
},
methods : {
clickme : function() {
alert("Anchor tag is clicked");
}
}
89
VueJS
});
</script>
</body>
</html>
Output
On the click of the link, it will display the alert message and does not open the url anymore.
Syntax
The key that we want to apply to our event is V-on.eventname.keyname (as shown
above)
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" s rc="js/vue.js"></script>
</head>
<body>
<div id="databinding">
90
VueJS
Output
91
VueJS
Type something in the textbox and we will see it is displayed only when we press Enter.
Custom Events
Parent can pass data to its component using the prop attribute, however, we need to tell
the parent when there are changes in the child component. For this, we can use custom
events.
The parent component can listen to the child component event using v-on attribute.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<div id="counter-event-example">
<p style="font-size:25px;">Language displayed :
<b>{{ languageclicked }}</b></p>
<button-counter
v-for="(item, index) in languages"
v-bind:item = "item"
v-bind:index="index"
v-on:showlanguage="languagedisp"></button-counter>
</div>
</div>
92
VueJS
<script type="text/javascript">
Vue.component('button-counter', {
template: '<button v-on:click="displayLanguage(item)"><span
style="font-size:25px;">{{ item }}</span></button>',
data: function () {
return {
counter: 0
}
},
props:['item'],
methods: {
displayLanguage: function (lng) {
console.log(lng);
this.$emit('showlanguage', lng);
}
},
});
var vm = new Vue({
el: '#databinding',
data: {
languageclicked: "",
languages : ["Java", "PHP", "C++", "C", "Javascript",
"C#", "Python", "HTML"]
},
methods: {
languagedisp: function (a) {
this.languageclicked = a;
}
}
})
</script>
</body>
</html>
93
VueJS
Output
The above code shows the data transfer between the parent component and the child
component.
<button-counter
v-for="(item, index) in languages"
v-bind:item = "item"
v-bind:index="index"
v-on:showlanguage="languagedisp"></button-counter>
There is a v-for attribute, which will loop with the languages array. The array has a list of
languages in it. We need to send the details to the child component. The values of the
array are stored in the item and the index.
v-bind:item = "item"
v-bind:index="index"
To refer to the values of the array, we need to bind it first to a variable and the varaiable
is referred using props property as follows.
Vue.component('button-counter', {
template: '<button v-on:click="displayLanguage(item)"><sp an
style="font-size:25px;">{{ item }}</span></button>',
data: function () {
return {
counter: 0
}
},
props:['item'],
94
VueJS
methods: {
displayLanguage: function (lng) {
console.log(lng);
this.$emit('showlanguage', lng);
}
},
});
The props property contains the item in an array form. We can also refer to the index as:
props:[‘item’, ‘index’]
<button-counter
v-for="(item, index) in languages"
v-bind:item = "item"
v-bind:index="index"
v-on:showlanguage="languagedisp"></button-counter>
The name of the event is showlanguage and it calls a method called languagedisp
which is defined in the Vue instance.
There is a button created. The button will get created with as many count in the language
array. On the click of the button, there is a method called displayLanguage and the button
clicked item is passed as a param to the function. Now the component needs to send the
clicked element to the parent component for display which is done as follows:
Vue.component('button-counter', {
template: '<button v-on:click="displayLanguage(item)"><span
style="font-size:25px;">{{ item }}</s pan></button>',
data: function () {
return {
counter: 0
}
95
VueJS
},
props:['item'],
methods: {
displayLanguage: functi on (lng) {
console.log(lng);
this.$emit('showlanguage', lng);
}
},
});
$emit is used to call the parent component method. The method showlanguage is the
event name given on the component with v-on.
<button-counter
v-for="(item, index) in languages"
v-bind:item = "item"
v-bind:index="index"
v-on:showlanguage="languagedisp"></button-counter>
We are passing a parameter, i.e. the name of the language clicked to the method of the
main parent Vue instance which is defined as follows.
96
VueJS
Here, the emit triggers showlanguage which in turn calls languagedisp from the Vue
instance methods. It assigns the language clicked value to the variable languageclic ke d
and the same is displayed in the browser as shown in the following screenshot.
97
11. VueJS - Rendering VueJS
In this chapter, we will learn about conditional rendering and list rendering. In conditional
rendering, we will discuss about using if, if-else, if-else-if, show, etc. In list rendering, we
will discuss how to use for loop.
Conditional Rendering
Let’s get started and work on a example first to explain the details for conditional
rendering. With conditional rendering, we want to output only when the condition is met
and the conditional check is done with the help of if, if-else, if-else-if, show, etc.
v-if
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<button v-on:click="showdata" v-bind:style="styleobj">Click
Me</button>
<span style="font-size:25px;"><b>{{show}}</b></span>
<h1 v-if="show">This is h1 tag</h1>
<h2>This is h2 tag</h2>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
show: true,
styleobj: {
backgroundColor: '#2196F3!important',
cursor: 'pointer',
padding: '8px 16px',
98
VueJS
verticalAlign: 'middle',
}
},
methods : {
showdata : function() {
this.show = !this.show;
}
},
});
</script>
</body>
</html>
Output
In the above example, we have created a button and two h1 tags with the message.
99
VueJS
A variable called show is declared and initialized to a value true. It is displayed close to
the button. On the click of the button, we are calling a method showdata, which toggles
the value of the variable show. This means on the click of the button, the value of the
variable show will change from true to false and false to true.
Now what it will do is, it will check the value of the variable show and if its true the h1 tag
will be displayed. Click the button and view in the browser, as the value of the show
variable changes to false, the h1 tag is not displayed in the browser. It is displayed only
when the show variable is true.
The h1 tag is removed from the DOM when the variable show is set to false.
100
VueJS
The h1 tag is added back to the DOM when the variable show is set to true.
v-else
In the following example, we have added v-else to the second h1 tag.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<button v-on:click="showdata" v-bind:style="styleobj">Click
Me</button>
<span style="font-size:25px;"><b>{{show}}</b></span>
<h1 v-if="show">This is h1 tag</h1>
<h2 v-else>This is h2 tag</h2>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
show: true,
styleobj: {
backgroundColor: '#2196F3!important',
cursor: 'pointer',
padding: '8px 16px',
verticalAlign: 'middle',
101
VueJS
}
},
methods : {
showdata : function() {
this.show = !this.show;
}
},
});
</script>
</body>
</html>
Now, if show is true “This is h1 tag” will be displayed, and if false “This is h2 tag” will
be displayed. This is what we will get in the browser.
102
VueJS
The above display is when the show variable is true. Since, we have added v-else, the
second statement is not present. Now, when we click the button the show variable will
become false and the second statement will be displayed as shown in the following
screenshot.
v-show
v-show behaves same as v-if. It also shows and hides the elements based on the condition
assigned to it. The difference between v-if and v-show is that v-if removes the HTML
element from the DOM if the condition is false, and adds it back if the condition is true.
Whereas v-show hides the element, if the condition is false with display:none. It shows
the element back, if the condition is true. Thus, the element is present in the dom always.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<button v-on:click="showdata" v-bind:style="styleobj">Click
Me</button>
<span style="font-size:25px;"><b>{{show}}</b></span>
<h1 v-if="show">This is h1 tag</h1>
<h2 v-else>This is h2 tag</h2>
103
VueJS
});
</script>
</body>
</html>
v-show is assigned to the HTML element using the following code snippet.
We have used the same variable show and based on it being true/false, the image is
displayed in the browser.
104
VueJS
Now, since the variable show is true, the image is as displayed in the above screenshot.
Let us click the button and see the display.
The variable show is false, hence the image is hidden. If we inspect and see the element ,
the div along with the image is still a part of the DOM with the style property display: none
as seen in the above screenshot .
105
VueJS
List Rendering
v-for
Let us now discuss list rendering with v-for directive.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<input type="text" v-on:keyup.enter="showinputvalue" v-
bind:style="styleobj" placeholder="Enter Fruits Names"/>
<h1 v-if="items.length>0">Display Fruits Name</h1>
<ul>
<li v-for="a in items">{{a}}</li>
<ul>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
items:[],
styleobj: {
width: "30%",
padding: "12px 20px",
margin: "8px 0",
boxSizing: "border-box"
}
},
methods : {
showinputvalue : function(event) {
this.items.push(event.target.value);
}
106
VueJS
},
});
</script>
</body>
</html>
We have used v-for to display the fruits entered as in the following piece of code. V-for
helps to iterate over the values present in the array.
<ul>
<li v-for="a in items">{{a}}</li>
<ul>
To iterate over the array with for loop, we have to use v-for=”a in items” where a holds
the values in the array and will display till all the items are done.
Output
107
VueJS
On inspecting the items, this is what it shows in the browser. In the DOM, we don’t see
any v-for directive to the li element. It displays the DOM without any VueJS directives.
108
VueJS
If we wish to display the index of the array, it is done using the following code.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<input type="text" v-on:keyup.enter="showinputvalue" v-
bind:style="styleobj" placeholder="Enter Fruits Names"/>
<h1 v-if="items.length>0">Display Fruits Name</h1>
<ul>
<li v-for="(a, index) in items">{{index}}--{{a}}</li>
<ul>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
items:[],
styleobj: {
width: "30%",
padding: "12px 20px",
margin: "8px 0",
boxSizing: "border-box"
}
},
methods : {
showinputvalue : function(event) {
this.items.push(event.target.value);
}
},
});
</script>
109
VueJS
</body>
</html>
To get the index, we have added one more variable in the bracket as shown in the following
piece of code.
In (a, index), a is the value and index is the key. The browser display will now be as
shown in the following screenshot. Thus, with the help of index any specific values can be
displayed.
110
12. VueJS - Transition & Animation VueJS
In this chapter, we will discuss the transition and animation features available in VueJS.
Transition
VueJS provides various ways to apply transition to the HTML elements when they are
added/updated in the DOM. VueJS has a built-in transition component that needs to be
wrapped around the element , which needs transition.
Syntax
<transition name="nameoftransition">
<div></div>
</transition>
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 2s
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version
2.1.8 */ {
opacity: 0
}
</style>
<div id="databinding">
<button v-on:click="show = !show">Click Me</button>
<transition name="fade">
111
VueJS
There is button called clickme created using which we can change the value of the variable
show to true to false and vice versa. There is a p tag which shows the text element only
if the variable is true. We have wrapped the p tag with the transition element as shown in
the following piece of code.
<transition name="fade">
<p v-show="show" v-bind:style="styleobj">Animation Example</p>
</transition>
The name of the transition is fade. VueJS provides some standard classes for transition
and the classes are prefixed with the name of the transition.
112
VueJS
v-enter: This class is called initially before the element is updated/added. Its the
starting state.
v-enter-active: This class is used to define the delay, duration, and easing curve
for entering in the transition phase. This is the active state for entire and the class
is available during the entire entering phase.
Each of the above classes will be prefixed with the name of the transition. We have given
the name of the transition as fade, hence the name of the classes becomes .fade_enter,
.fade_enter_active, .fade_leave, .fade_leave_active.
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 2s
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version
2.1.8 */ {
opacity: 0
}
</style>
The duration is defined in the .fade_enter_active and .fade_leave_active. The final stage
is defined in the .fade_enter, .fade_leave_to.
113
VueJS
On the click of the button, the text will fade away in two seconds.
Let us consider another example, where there is an image and it is shifted on the x-axis
when the button is clicked.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
114
VueJS
.shiftx-enter-active, .shiftx-leave-active {
transition: all 2s ease-in-out;
}
.shiftx-enter, .shiftx-leave-to /* .fade-leave-active below
version 2.1.8 */ {
transform : translateX(100px);
}
</style>
<div id="databinding">
<button v-on:click="show = !show">Click Me</button>
<transition name="shiftx">
<p v-show="show"><img src="images/img.jpg"
style="width:100px;height:100px;" /></p>
</transition>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
show:true
},
methods : {
}
});
</script>
</body>
</html>
115
VueJS
The name of the transition is shiftx. A transform property is used to shift the image on
the x-axis by 100px using the following piece of code.
<style>
.shiftx-enter-active, .shiftx-leave-active {
transition: all 2s ease -in-out;
}
.shiftx-enter, .shiftx-leave-to /* .fade-leave-active below
version 2.1.8 */ {
transform : translateX(100px);
}
</style>
On the click of the button, the image will shift 100px towards the right as shown in the
following screenshot.
116
VueJS
Animation
Animations are applied the same way as transition is done. Animation also has classes
that needs to be declared for the effect to take place.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
.shiftx-enter-active {
animation: shift-in 2s;
}
.shiftx-leave-active {
animation: shift-in 2s reverse;
}
@keyframes shift-in {
117
VueJS
0% {transform:rotateX(0deg);}
25% {transform:rotateX(90deg);}
50% {transform:rotateX(120deg);}
75% {transform:rotateX(180deg);}
100% {transform:rotateX(360deg);}
}
</style>
<div id="databinding">
<button v-on:click="show = !show">Click Me</button>
<transition name="shiftx">
<p v-show="show"><img src="images/img.jpg"
style="width:100px;height:100px;" /></p>
</transition>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
show:true
},
methods : {
}
});
</script>
</body>
</html>
To apply animation, there are classes same as transition. In the above code, we have an
image enclosed in p tag as shown in the following piece of code.
<transition name="shiftx">
<p v-show="show"><img src="images/img.jpg"
style="width:100px;height:100px;" /></p>
</transition>
118
VueJS
<style>
.shiftx-enter-active {
animation: shift-in 2s;
}
.shiftx-leave-active {
animation: shift-in 2s reverse;
}
@keyframes shift-in {
0% {transform:rotateX(0deg);}
25% {transform:rotateX(90deg);}
50% {transform:rotateX(120deg);}
75% {transform:rotateX(180deg);}
100% {transform:rotateX(360deg);}
}
</style>
The class is prefixed with the transition name, i.e. shiftx-enter-active and .shiftx-leave-
active. The animation is defined with the keyframes from 0% to 100%. There is a
transform defined at each of the keyframes is as shown in the following piece of code.
@keyframes shift-in {
0% {transform:rotateX(0deg);}
25% {transform:rotateX(90deg);}
50% {transform:rotateX(120deg);}
75% {transform:rotateX(180deg);}
100% {transform:rotateX(360deg);}
}
119
VueJS
120
VueJS
enter-class
enter-active-class
leave-class
leave-active-class
Custom classes basically come into play when we want to use an external CSS library such
as animate.css.
Example
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1"
rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="animate" style="text-align:center">
<button @click="show = !show"><span style="font -
size:25px;">Animate</span></button>
<transition
name="custom-classes-transition"
enter-active-class="animated swing"
leave-active-class="animated bounceIn">
<p v-if="show"><span style="font-size:25px;">Example</span></p>
</transition>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#animate',
data: {
show: true
}
});
121
VueJS
</script>
</body>
</html>
Output
Output
122
VueJS
Output
There are two animations applied in the above code. One enter-active-class = “animat ed
swing” and another leave-active-class=”animated bounceIn”. We are making the use of
custom animation classes for the animation to be applied from the third party library.
Sometimes the transition can cause delay. In such cases, we can apply the duration
explicitly as follows.
<transition :duration="1000"></transition>
<transition :duration="{ enter: 500, leave: 800 }">...</transition>
We can use the duration property with a : on the transition element as shown above. In
case there is a need to specify the duration separately for entering and leaving, it can be
done as shown in the above piece of code.
123
VueJS
JavaScript Hooks
The transition classes can be called as methods using JavaScript events. Let us consider
an example for better understanding.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></s
cript>
<div id="example-4">
<button @click="show = !show">
<span style="font-size:25px;">Toggle</span>
</button>
<transition v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:leave="leave"
v-bind:css="false"
><p v-if="show" style="font-size:25px;">Animation Example with
velocity</p></transition>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#example-4',
data: {
show: false
},
methods: {
beforeEnter: function (el) {
el.style.opacity = 0
},
enter: function (el, done) {
124
VueJS
125
VueJS
Output
126
VueJS
In the above example, we are performing animation using js methods on the transition
element.
<transition v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:leave="leave"
v-bind:css="false"
><p v-if="show" style="font-size:25px;">Animation Example with
velocity</p></transition>
There is a prefix added v-on and the name of the event to which the method is called.
The methods are defined in the Vue instance as follows:
methods: {
beforeEnter: function (el) {
el.style.opacity = 0
},
enter: function (el, done) {
Velocity(el, { opacity: 1, fontSize: '25px' },
{ duration: 1000 })
Velocity(el, { fontSize: '10px' }, { complete: done })
},
leave: function (el, done) {
Velocity(el, { translateX: '15px', rotateZ: '50deg' },
{ duration: 1500 })
Velocity(el, { rotateZ: '100deg' }, { loop: 2 })
Velocity(el, {
rotateZ: '45deg',
translateY: '30px',
translateX: '30px',
opacity: 0
}, { complete: done })
}
}
127
VueJS
The required transition is applied in each of these methods. There is an opacity animat ion
applied on the click of the button and also when the animation is done. Third party library
is used for animation.
Example
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1"
rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="animate" style="text-align:center">
<transition
appear
appear-class="custom-appear-class"
appear-active-class="animated bounceIn">
<h1>BounceIn - Animation Example</h1>
</transition>
<transition
appear
appear-class="custom-appear-class"
appear-active-class="animated swing">
<h1>Swing - Animation Example</h1>
</transition>
<transition
appear
appear-class="custom-appear-class"
appear-active-class="animated rubberBand">
<h1>RubberBand - Animation Example</h1>
128
VueJS
</transition>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#animate',
data: {
show: true
}
});
</script>
</body>
</html>
In the above example, we have used three different animations from animate.css library.
We have added appear to the transition element .
On execution of the above code, following will be the output in the browser.
129
VueJS
Animation on Components
We can wrap the transition for the components using the following code. We have used
dynamic component here.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1"
rel="stylesheet" type="text/css">
</head>
<body>
<div id="databinding" style="text-align:center;">
<transition appear
appear-class="custom-appear-class"
appear-active-class="animated wobble">
<component v-bind:is="view"></component>
</transition>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
view: 'component1'
},
components: {
'component1': {
template: '<div><span style="font-
130
VueJS
size:25;color:red;">Animation on Components</span></div>'
}
}
});
</script>
</body>
</html>
Output
131
13. VueJS - Directives VueJS
Directives are instruction for VueJS to do things in a certain way. We have already seen
directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc.
In this chapter, we will take a look at custom directives. We will create global directives
similar to how we did for components.
Syntax
Vue.directive('nameofthedirective', {
bind(e1, binding, vnode) {
}
})
We need to create a directive using Vue.directive. It takes the name of the directive as
shown above. Let us consider an example to show the details of the working of directives.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<div v-changestyle>VueJS Directive</div>
</div>
<script type="text/javascript">
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
e1.style.color="red";
e1.style.fontSize="30px";
}
});
132
VueJS
</script>
</body>
</html>
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
e1.style.color="red";
e1.style.fontSize="30px";
}
});
If we see in the browser, it will display the text VueJs Directive in red color and the fontsize
is increased to 30px.
133
VueJS
Output
We have used the bind method, which is a part of the directive. It takes three argument s
e1, the element to which the custom directive needs to be applied. Binding is like
arguments passed to the custom directive, e.g. v-changestyle=”{color:’green’}”, where
green will be read in the binding argument and vnode is the element , i.e. nodename.
In the next example, we have consoled all the arguments and its shows what details each
of them give.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<div v-changestyle="{color:'green'}">VueJS Directive</div>
</div>
<script type="text/javascript">
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
console.log(binding.value.color);
console.log(vnode);
e1.style.color=binding.value.color;
e1.style.fontSize="30px";
}
});
134
VueJS
},
methods : {
},
});
</script>
</body>
</html>
Output
The color of the text is changed to green. The value is passed using the following piece of
code.
135
VueJS
Vue.directive("changestyle",{
bind(e1,binding, vnode) {
console.log(e1);
console.log(binding.value.color);
console.log(vnode);
e1.style.color=binding.value.color;
e1.style.fontSize="30px";
}
});
Filters
VueJS supports filters that help with text formatting. It is used along with v-bind and
interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for
filters.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
<input v-model="name" placeholder="Enter Name" /><br/>
<span style="font-size:25px;"><b>Letter count is : {{name |
countletters}}</b></span>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
name : ""
},
filters : {
136
VueJS
countletters : function(value) {
return value.length;
}
}
});
</script>
</body>
</html>
In the above example, we have created a simple filter countletters. Countletters filter
counts the numbers of characters entered in the textbox. To make use of filters, we need
to use the filter property and define the filter used, by the following piece of code.
filters : {
countletters : function(value) {
return value.length;
}
}
We are defining the method countletters and returning the length of the string entered.
To use filter in the display, we have used the pipe operator and the name of the filter, i.e.
countletters.
137
VueJS
We can also pass arguments to the filter using the following piece of code.
Now, the countletters will have three params, i.e. message, a1, and a2.
We can also pass multiple filters to the interpolation using the following piece of code.
In the filter property countlettersA and countlettersB will be the two methods and the
countlettersA will pass the details to countlettersB.
138
14. VueJS - Routing VueJS
VueJS does not have a built-in router feauture. We need to follow some additional steps
to install it.
Unpkg.com provides npm-based cdn links. The above link is always updated to the recent
version. We can download and host it , and use it with a script tag along with vue.js as
follows:
<script src="/path/to/vue.js"></script>
<script src="/path/to/vue -router.js"></script>
Using NPM
Run the following command to install the vue-router.
Using GitHub
We can clone the repository from GitHub as follows:
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/vue-router.js"></script>
139
VueJS
</head>
<body>
<div id="app">
<h1>Routing Example</h1>
<p>
<router-link to="/route1">Router Link 1</router-link>
<router-link to="/route2">Router Link 2</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
<script type="text/javascript">
const Route1 = { template: '<div style="border-
radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-
size:25px;padding:10px;">This is router 1</div>' }
const Route2 = { template: '<div style="border -
radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-
size:25px;padding:10px;">This is router 2</div>' }
const routes = [
{ path: '/route1', component: Route1 },
{ path: '/route2', component: Route2 }
];
const router = new VueRouter({
routes // short for `routes: routes`
});
var vm = new Vue({
el: '#app',
router
});
</script>
</body>
</html>
140
VueJS
Output
141
VueJS
To start with routing, we need to add the vue-router.js file. Take the code from
https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.js.
<p>
<router-link to="/route1">Router Link 1</router-link>
<router-link to="/route2">Router Link 2</router-link>
</p>
Take a look at the script section where the router is initialized. There are two constants
created as follows:
They have templates, which needs to be shown when the router link is clicked.
Next, is the routes const, which defines the path to be displayed in the URL.
const routes = [
{ path: '/route1', component: Route1 },
{ path: '/route2', component: Route2 }
];
Routes define the path and the component . The path i.e. /route1 will be displayed in the
URL when the user clicks on the router link.
142
VueJS
Component takes the templates names to be displayed. T he path from the routes need to
match with the router link to the property.
Next, the instance is created to VueRouter using the following piece of code.
The VueRouter constructor takes the routes as the param. The router object is assigned
to the main vue instance using the following piece of code.
Execute the example and see the display in the browser. On inspecting and checking the
router link, we will find that it adds class to the active element as shown in the following
screenshot.
143
VueJS
to
This is the destination path given to the <router-link>. When clicked, the value of to will
be passed to router.push() internally. The value needs to be a string or a location object.
When using an object, we need to bind it as shown in e.g. 2.
144
VueJS
replace
Adding replace to the router link will call the router.replace() instead of router.push().
With replace, the navigation history is not stored.
Example
append
Adding append to the <router-link><router-link> will make the path relative.
If we want to go from the router link with path /route1 to router link path /route2, it will
show the path in the browser as /route1/route2.
Example
tag
At present <router-link> renders as a tag. In case, we want to render it as some other
tag, we need to specifty the same using tag=”tagname”;
Example
<p>
<router-link v-bind:to="{ path: '/route1'}" tag="span">Router Link 1</router -
link>
<router-link v-bind:to="{ path: '/route2'}" tag="span">Router Link 2</router -
link>
</p>
We have specified the tag as span and this is what is displayed in the browser.
145
VueJS
The tag displayed now is a span tag. We will still see the click going as we click on the
router link for navigation.
active-class
By default, the active class added when the router link is active is router-link-active. We
can overwrite the class by setting the same as shown in the following code.
<style>
._active{
background-color : red;
}
</style>
<p>
<router-link v-bind:to="{ path: '/route1'}" active-class="_active">Router Link
1</router-link>
<router-link v-bind:to="{ path: '/route2'}" tag="span">Router Link 2</router -
link>
</p>
The class used is active_class=”_active”. This is the output displayed in the browser.
exact-active-class
The default exactactive class applied is router-link-exact-active. We can overwrite it using
exact-active-class.
146
VueJS
Example
<p>
<router-link v-bind:to="{ path: '/route1'}" exact -active-class="_active">Router
Link 1</router-link>
<router-link v-bind:to="{ path: '/route2'}" tag="span">Router Link 2</router -
link>
</p>
event
At present, the default event for router-link is click event. We can change the same using
the event property.
Example
Now, when we mouseover the router link, it will navigate as shown in the following
browser. Mouseover on the Router link 1 and we will see the navigation changing.
147
VueJS
148
15. VueJS – Mixins VueJS
Mixins are basically to be used with components. They share reusable code among
components. When a component uses mixin, all options of mixin become a part of the
component options.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
},
methods : {
},
});
var myMixin = {
created: function () {
this.startmixin()
},
methods: {
startmixin: function () {
alert("Welcome to mixin example");
}
149
VueJS
}
};
Output
When a mixin and a component contain overlapping options, they are merged as shown
in the following example.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
</div>
<script type="text/javascript">
var mixin = {
created: function () {
console.log('mixin called')
150
VueJS
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('component called')
}
});
</script>
</body>
</html>
Now the mixin and the vue instance has the same method created. This is the output we
see in the console. As seen, the option of the vue and the mixin will be merged.
If we happen to have the same function name in methods, then the main vue instance will
take priority.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="databinding">
</div>
151
VueJS
<script type="text/javascript">
var mixin = {
methods: {
hellworld: function () {
console.log('In HelloWorld');
},
samemethod: function () {
console.log('Mixin:Same Method');
}
}
};
var vm = new Vue({
mixins: [mixin],
methods: {
start: function () {
console.log('start method');
},
samemethod: function () {
console.log('Main: same method');
}
}
});
vm.hellworld();
vm.start();
vm.samemethod();
</script>
</body>
</html>
We will see mixin has a method property in which helloworld and samemethod functions
are defined. Similarly, vue instance has a methods property in which again two methods
are defined start and samemethod.
152
VueJS
vm.hellworld(); // In HelloWorld
vm.start(); // start method
vm.samemethod(); // Main: same method
As seen above, we have called helloworld, start , and samemethod function. samemet hod
is also present in mixin, however, priority will be given to the main instance, as seen in
the following console.
153
16. VueJS - Render Function VueJS
We have seen components and the usage of it. For example, we have a content that needs
to be reused across the project. We can convert the same as a component and use it.
Let’s take a look at an example of a simple component and see what the render function
has to do within it.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="component_test">
<testcomponent></testcomponent>
</div>
<script type="text/javascript">
Vue.component('testcomponent',{
template : '<h1>Hello World</h1>',
data: function() {
},
methods:{
}
});
154
VueJS
Consider the above example of a simple component that prints Hello World as shown in
the following screenshot.
Now, if we want to reuse the component , we can do so by just printing it again. For
example,
<div id="component_test">
<testcomponent></testcomponent>
<testcomponent></testcomponent>
<testcomponent></testcomponent>
<testcomponent></testcomponent>
</div>
155
VueJS
However, now we need some changes to the component. We don’t want the same text to
be printed. How can we change it? In case, we type something inside the component , will
it be take into consideration?
<div id="component_test">
<testcomponent>Hello Jai</testcomponent>
<testcomponent>Hello Roy</testcomponent>
<testcomponent>Hello Ria</testcomponent>
<testcomponent>Hello Ben</testcomponent>
</div>
The output remains the same as we had seen earlier. It does not change the text as we
want.
Component does provide something called as slots. Let’s make use of it and see if we get
the desired results.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="component_test">
156
VueJS
<testcomponent>Hello Jai</testcomponent>
<testcomponent>Hello Roy</testcomponent>
<testcomponent>Hello Ria</testcomponent>
<testcomponent>Hello Ben</testcomponent>
</div>
<script type="text/javascript">
Vue.component('testcomponent',{
template : '<h1><slot></slot></h1>',
data: function() {
},
methods:{
}
});
As seen in the above code, in the template we have added slot, hence now it takes the
value to send inside the component as shown in the following screenshot.
157
VueJS
Now, let us consider we want to change the color and size. For example, currently we are
using h1 tag and we want to change the HTML tag to p tag or div tag for the same
component. How can we have the flexibility to carry out so many changes?
We can do so with the help of the render function. Render function helps make the
component dynamic and use the way it is required by keeping it common and helping pass
arguments using the same component.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="component_test">
<testcomponent :elementtype="'div,red,25,div1'">Hello
Jai</testcomponent>
<testcomponent :elementtype="'h3,green,25,h3tag'">Hello
Roy</testcomponent>
<testcomponent :elementtype="'p,blue,25,ptag'">Hello
Ria</testcomponent>
158
VueJS
<testcomponent :elementtype="'div,green,25,divtag'">Hello
Ben</testcomponent>
</div>
<script type="text/javascript">
Vue.component('testcomponent',{
render :function(createElement){
var a = this.elementtype.split(",");
return createElement(a[0],
{
attrs:{
id:a[3],
style:"color:"+a[1]+";font -size:"+a[2]+";"
}
},
this.$slots.default
)
},
props:{
elementtype:{
attributes:String,
required:true
}
}
});
159
VueJS
In the above code, we have changed the component and added the render function with
props property using the following piece of code.
Vue.component('testcomponent',{
render :function(createElement){
var a = this.elementtype.split(",");
return createElement(a[0],
{
attrs:{
id:a[3],
style:"color:"+a[1]+";font -size:"+a[2]+";"
}
},
this.$slots.default
)
},
props:{
elementtype:{
attributes:String,
required:true
}
}
});
props:{
elementtype:{
attributes:String,
required:true
}
}
We have defined a property called elementtype, which takes attributes field of type string.
Another required field, which mentions that the field is mandatory.
160
VueJS
In the render function, we have used the elementtype property as seen in the following
piece of code.
render :function(createElement){
var a = this.elementtype.split(",");
return createElement(a[0],
{
attrs:{
id:a[3],
style:"color:"+a[1]+";font -size:"+a[2]+";"
}
},
this.$slots.default
)
}
Render function takes createElement as the argument and returns the same.
CreateElement creates the DOM element the same way as in JavaScript . We have also
split the elementtype on comma, using the values in the attrs field.
The component needs to take the props field as shown above. It starts with : and the
name of the props. Here, we are passing the element tag, color, fontsize, and the id of the
element.
161
VueJS
return createElement(a[0],
{
attrs:{
id:a[3],
style:"color:"+a[1]+";font-size:"+a[2]+";"
}
},
this.$slots.default
)
a[0] is the html element tag. The next parameter is the attributes for the element tag.
They are defined in the attr field in the following piece of code.
attrs:{
id:a[3],
style:"color:"+a[1]+";font-size:"+a[2]+";"
}
We have defined two attributes for the element tag - id and style. To id, we are passing
a[3], which is the value we have after splitting on comma. Using style, we have defined
color and fontsize.
Last is the slot, that is the message we have given in the component in the following piece
of code.
We have defined the text to be printed in the createElement using the following piece of
code.
this.$slots.default
162
VueJS
The elements also show the structure. These are the components we have defined:
<div id="component_test">
<testcomponent :elementtype="'div,red,25,div1'">Hello
Jai</testcomponent>
<testcomponent :elementtype="'h3,green,25,h3tag'">Hello
Roy</testcomponent>
<testcomponent :elementtype="'p,blue,25,ptag'">Hello
Ria</testcomponent>
<testcomponent :elementtype="'div,green,25,divtag'">Hello
Ben</testcomponent>
</div>
163
17. VueJS – Reactive Interface VueJS
VueJS provides options to add reactivity to properties, which are added dynamically.
Consider that we have already created vue instance and need to add the watch property.
It can be done as follows:
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<p style="font-size:25px;">Counter: {{ counter }}</p>
<button @click="counter++" style="font-size:25px;">Click
Me</button>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
counter: 1
}
});
setTimeout(
function(){
vm.counter = 20;
164
VueJS
},2000
);
</script>
</body>
</html>
There is a property counter defined as 1 in data object. The counter is incremented when
we click the button.
We need to use $watch to add watch outside the vue instance. There is an alert added,
which shows the value change for the counter property. There is also a timer function
added, i.e. setTimeout, which sets the counter value to 20.
setTimeout(
function(){
vm.counter = 20;
},2000
);
Whenever the counter is changed, the alert from the watch method will get fired as shown
in the following screenshot.
165
VueJS
VueJS cannot detect property addition and deletion. The best way is to always declare the
properties, which needs to be reactive upfront in the Vue instance. In case we need to add
properties at run time, we can make use of Vue global, Vue.set, and Vue.delete methods.
Vue.set
This method helps to set a property on an object . It is used to get around the limitation
that Vue cannot detect property additions.
Syntax
Where,
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<p style="font-size:25px;">Counter: {{ products.id }}</p>
<button @click="products.id++" style="font-size:25px;">Click
Me</button>
</div>
<script type="text/javascript">
var myproduct = {"id":1, name:"book", "price":"20.00"};
var vm = new Vue({
el: '#app',
data: {
counter: 1,
products: myproduct
}
166
VueJS
});
vm.products.qty="1";
console.log(vm);
vm.$watch('counter', function(nval, oval) {
alert('Counter is incremented :' + oval + ' to ' + nval +
'!');
});
</script>
</body>
</html>
In the above example, there is a variable myproduct created at the start using the
following piece of code.
Consider, we want to add one more property to the myproduct array, after the Vue
instance is created. It can be done as follows:
vm.products.qty="1";
167
VueJS
As seen above, in products the quantity is added. The get/set methods, which basically
adds reactivity is available for the id, name, and price, and not available for qty.
We cannot achieve the reactivity by just adding vue object. VueJS mostly wants all its
properties to be created at the start. However, in case we need to add it later, we can use
Vue.set. For this, we need to set it using vue global, i.e. Vue.set.
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<p style="font-size:25px;">Counter: {{ products.id }}</p>
<button @click="products.id++" style="font-size:25px;">Click
Me</button>
</div>
<script type="text/javascript">
var myproduct = {"id":1, name:"book", "price":"20.00"};
var vm = new Vue({
168
VueJS
el: '#app',
data: {
counter: 1,
products: myproduct
}
});
</script>
</body>
</html>
We have used Vue.set to add the qty to the array using the following piece of code.
169
VueJS
Now, we can see the get/set for qty added using Vue.set.
Vue.delete
This function is used to delete the property dynamically.
Example
Vue.delete( target, key )
Where,
Example
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<p style="font-size:25px;">Counter: {{ products.id }}</p>
<button @click="products.id++" style="font-size:25px;">Click
Me</button>
</div>
<script type="text/javascript">
var myproduct = {"id":1, name:"book", "price":"20.00"};
var vm = new Vue({
el: '#app',
data: {
counter: 1,
products: myproduct
}
});
Vue.delete(myproduct, 'price');
console.log(vm);
170
VueJS
</script>
</body>
</html>
In the above example, we have used Vue.delete to delete the price from the array using
the following piece of code.
Vue.delete(myproduct, 'price');
After deletion, we can see only the id and name as the price is deleted. We can also notice
that the get/set methods are deleted.
171
18. VueJS – Examples VueJS
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
#databinding{
padding: 20px 15px 15px 15px;
margin: 0 0 25px 0;
width: auto;
background-color: #e7e7e7;
}
span, option, input {
font-size:25px;
}
</style>
<div id="databinding" style="">
<h1>Currency Converter</h1>
<span>Enter Amount:</span><input type="number" v-
model.number="amount" placeholder="Enter Amount" /><br/><br/>
<span>Convert From:</span>
<select v-model="convertfrom" style="width:300px;font-size:25px;">
<option v-for="(a, index) in currencyfrom" v-
bind:value="a.name">{{a.desc}}</option>
</select>
<span>Convert To:</span>
<select v-model="convertto" style="width:300px;font-size:25px;">
172
VueJS
173
VueJS
}
if (to == "BHD") {
final = this.amount * 0.0059;
}
break;
case "USD":
if (to == "INR") {
final = this.amount * 63.88;
}
if (to == "EUR") {
final = this.amount * 0.84;
}
if (to == "USD") {
final = this.amount;
}
if (to == "BHD") {
final = this.amount * 0.38;
}
break;
case "EUR":
if (to == "INR") {
final = this.amount * 76.22;
}
if (to == "USD") {
final = this.amount * 1.19;
}
if (to == "EUR") {
final = this.amount;
}
if (to == "BHD") {
final = this.amount * 0.45;
}
break;
case "BHD":
if (to == "INR") {
174
VueJS
175
VueJS
Explanation: In the above example, we have c reated a currency converter that converts
one value of currency to the selected value of other currency. We have created two
dropdowns of currency. When we enter the amount to convert in the textbox, the same is
displayed below after conversion. We are using the computed property to do the necessary
calculation for currency conversion.
<html>
<head>
<title>VueJs Instance</title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<style>
#databinding{
padding: 20px 15px 15px 15px;
margin: 0 0 25px 0;
width: auto;
}
span, option, input {
font-size:20px;
}
.Table
{
176
VueJS
display: table;
width:80%;
}
.Title
{
display: table-caption;
text-align: center;
font-weight: bold;
font-size: larger;
}
.Heading
{
display: table-row;
font-weight: bold;
text-align: center;
}
.Row
{
display: table-row;
}
.Cell
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 5px;
padding-right: 5px;
width:30%;
}
</style>
<div id="databinding" style="">
<h1>Customer Details</h1>
<span>First Name</span>
<input type="text" placeholder="Enter First Name" v-model="fname"/>
<span>Last Name</span>
177
VueJS
178
VueJS
} else {
return "#D4CA87";
}
}
}
});
179
VueJS
</body>
</html>
Output
Explanation: In the above example, we have three texboxes to enter - the First Name,
Last Name and Address. There is an add button, which adds the values entered in the
textboxes in a table format with a delete button.
The table format is created using components. The click button interacts with the parent
component using the emit event to delete the elemet from the array. The values entered
are stored in the array and the same are shared with the child component using the prop
property.
180