Vue.js 2 Authentication Tutorial, Part 1
In Part 1 of this 3 part series, we introduce Vue.js, how it compares to other JavaScript frameworks, and show a bit of the code you can employ with it.
Join the DZone community and get the full member experience.
Join For FreeVue.js was developed by Evan You, an ex-Google software engineer. Just before launching Vue.js 2.0, he started to work on Vue.js full time and as a result, Vue.js 2 is now significantly lighter, smaller in size, and faster. Currently, many popular products use Vue.js to build their user interfaces. Such platforms include Laravel Spark, Grammarly, Statamic, Laracasts, and more. There is a comprehensive list of projects using Vue.js on Github. Vue.js 2's documentation is very detailed, and there is a vibrant community of users.
Vue.js 2, Angular 2, and React
Vue.js was inspired by AngularJS in its early days of development, thus making some of its syntaxes look very similar to AngularJS, e.g. v-show
, v-if
and v-for
. Angular 2 came onto the scene with a completely new framework in terms of API design, underlying language, and many add-ons, which was initially disturbing for a lot of developers. Now Vue.js 2, despite being a full rewrite, made its API largely compatible with Vue.js 1.0, thus making it super easy for developers to transition from Vue.js 1.0 to 2.0. Whoop! Whoop!
Vue.js 2.0 comes bundled with some major changes:
- The rendering layer is now based on a lightweight virtual-DOM implementation, Snabbom.
- Detection of static class names and attributes so that they are never diff after the initial render.
- Detection of subtrees without dynamic bindings and hoisting them out of the render function, which as a result leads to diff skipping on each re-render.
- It supports server-side rendering with client-side hydration. React and Angular 2 also provides server-side rendering.
- Support for JSX. The template syntax is still available for use, but you can always drop down to the virtual-DOM layer whenever you feel constrained by the use of templates.
- The template-to-virtual-DOM compiler and the runtime can be separated, so you can pre-compile templates and ship your app with only the runtime, which is less than 12kb min+gzip.
AngularJS(Angular 1) uses two-way binding between scopes, while Vue enforces a one-way data flow between components.
Vue.js 2 and Angular 2 are similar in a way because they both offer component-based systems.
React and Vue.js are also similar in many ways. They both:
- Utilize a virtual DOM.
- Provide composable view components.
- Have a core library and have sister libraries for handling state, routing, network requests, etc.
Enter Performance Profiling
Vue.js and React utilize virtual DOM, but Vue's virtual DOM implementation allows rendering of UI to be faster than that of React because it involves less overhead. Let's look at some performance statistics done by the Vue.js team. Check out the repo here.
This benchmark was run 20 times with results from the best runs on a 2014 MacBook Air.
Vue, React Metrics
By default, React triggers a re-render of an entire component subtree when the state changes. To avoid unnecessary re-rendering, you have to manually implement shouldComponentUpdate
. In Vue.js, a component’s dependencies are automatically tracked during its render, so the system knows precisely which components actually need to re-render.
According to this benchmark, Vue 2's app size is smaller than Angular 2.
Understanding Key Concepts in Vue.js 2
Vue.js 2 is similar to React and Angular 2 in a few ways. There are few key concepts that will help you get started easily. I'll give a basic overview of these concepts to nourish your understanding of Vue.js. They are:
- Directives
- Components
- Template/JSX
You can decide to use Vue.js 2 by simply invoking methods on a Vue instance or by going the component-composing route.
<div id="app">
<p></p>
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello, it is this easy!'
}
})
The result of the code above on the browser will be Hello, it is this easy!. The value of any property in the data object within a new Vue instance will be rendered to the DOM easily. The curly braces `` are used to display the property on the web page.
Directives
It's very easy to toggle the display of items on a web page with inbuilt directives such as v-if
, v-show
like so:
<div id="app">
<p v-if="visible()"></p>
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello, it is this easy!'
},
methods: {
visible: function() {
return true;
}
}
});
If for any reason, the visible
function returns false, the paragraph would not be displayed on the web page. What about iterations and loops? Check out the code below:
<div id="app">
<ol>
<li v-for="item in items">
</li>
</ol>
</div>
var app = new Vue({
el: '#app',
data: {
items: [
{ name: 'Prosper Otemuyiwa' },
{ name: 'Goodness Kintakunte' },
{ name: 'Lynda' }
]
}
});
On the page, it will simply display:
Prosper Otemuyiwa
Goodness Kintakunte
Lynda
Components
Vue.js 2 also leverages components. It allows you to build large applications composed of small, self-contained smaller components.
An example of a component is an HTML5 tag, say <header>
. A header can have attributes, it can be styled and also possess its own behavior. In Vue.js 2, you'll be able to build your own custom component by registering it like so:
Vue.component('app-nav', {
template: "<li>This is the application's navbar</li>"
})
Then, you can use it in another component like so:
<div>
<app-nav></app-nav>
</div>
So, your component will now be <app-nav></app-nav>
.
Vue.js 2 provides some methods that are triggered at various points from creating a component up until the component is destroyed. This is called the Instance Lifecycle, also known as the Component's Lifecycle. Each Vue instance goes through a series of initialization steps when it is created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. So you can execute custom logic in these hooks. These lifecycle hooks are: beforeCreate
, created
, beforeMount
, mounted
, beforeUpdate
, updated
, activated
, deactivated
, beforeDestroy
and destroyed
.
Vue.js 2 Lifecycle hooks
- beforeCreate() : This method is called synchronously after the Vue instance has just been initialized, before data observation and event/watcher setup.
- created() : This method is called synchronously after the Vue instance is created. Data observation, computed properties, methods and event callbacks have already been set up at this stage but the mounting phase has not started yet.
- beforeMount() : This method is called right before the component is mounted. So it is called before the
render
method is executed. - mounted() : This method is called after the component has just been mounted.
- beforeUpdate() : This method is called when the data changes, before the virtual DOM is re-rendered and patched.
- updated() : This method is called after a data change causes the virtual DOM to be re-rendered and patched.
- activated() : This method is called when a kept-alive component is activated.
- deactivated() : This method is called when a kept-alive component is deactivated.
- beforeDestroy() : This method is called right before a Vue instance or component is destroyed. At this stage, the instance is still fully functional.
- destroyed() : This method is called after a Vue instance or component has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed.
Vue.js 2 possess some built-in components such as component
, transition
, transition-group
, keep-alive
and slot
. You can take advantage of these components in your app. Check out how to use them.
Props
Props
is the short form for properties
. Properties are attributes of a component. In fact, props are how components talk to each other. A tag in HTML such as <img>
has an attribute, a.k.a. a prop
called src
that points to the location of an image.
In Vue.js 2, you can pass data from the parent scope into child components. A typical example is this:
Vue.component('tag-list', {
props: ['item'],
template: '<li></li>'
})
var app = new Vue({
el: '#app',
data: {
tagList: [
{ tag: '5kbae' },
{ tag: 'Based on Logistics' },
{ tag: 'Image management' }
]
}
})
<div id="app">
<ol>
<tag-list v-for="list in tagList" v-bind:item="list"></todo-item>
</ol>
</div>
It will display these items on the web page like so:
5kbae
Based on Logistics
Image management
Template/JSX
Vue.js 2 uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data. All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers.
You can also decide to use JSX. JSX is the combination of HTML and JavaScript code in the same file. The browser is not meant to understand it. It must first be transpiled into standard JavaScript before the browser can understand. An example of JSX usage in Vue.js is:
data: {
text: 'Hello world'
},
render (h) {
return (
<div id='message'>,
{ this.text }
</div>
);
}
Now, by default, Vue doesn't support JSX, but with the help of babel-plugin-transform-vue-jsx we can use JSX with Vue. Oh, the ecosystem should be thanked for this great tool. Whoop! Whoop!
With Vue 2, you can use the render
function to create a reactive element. And you can use JSX in it like so:
new Vue({
el: '#app',
data: {
msg: 'Click to see the message.'
},
methods: {
hello () {
alert('This is the message.')
}
},
render: function render(h) {
return (
<span
class=my-class-3
style=
on-click={ this.hello }
>
{ this.msg }
</span>
)
}
});
Can you see the power of JSX manifesting itself in Vue? Awesome! You can check out more information on JSX in Vue here.
In my next post, we'll go over how to build an application with Vue.js 2.
Published at DZone with permission of Prosper Otemuyiwa, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
RBAC With API Gateway and Open Policy Agent (OPA)
-
Extending Java APIs: Add Missing Features Without the Hassle
-
Database Integration Tests With Spring Boot and Testcontainers
-
The SPACE Framework for Developer Productivity
Comments