Saturday, April 9, 2022

5 Practical Examples For Learning Vue.js


 
Download

We've already covered Angular.js and React in previous articles but there is a new frontend library that we think is worth your time. It's called Vue.js and it has gathered a large community of enthusiastic developers.

The philosophy behind Vue.js is to provide the simplest possible API for creating real-time, two-way data binding between the view (HTML) and the model (a JavaScript object). As you will see in the following examples, the library holds true to that idea and working with it is effortless and enjoyable, without compromising on any functionality.

This article has been updated and now works with Vue.js v2!

Getting Started

The easiest way to install Vue.js is to simply include it with a <script> tag at the end of your HTML's body. The entire library is located in a single JavaScript file which you can download from the official website or import directly via CDN:

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

If you want to use the library in a Node.js project, vue is available as an npm module. There is also an official CLI, which allows users to quickly setup their whole project based on premade template builds.

Below are five editors containing example apps we've built for you. The code has lots of comments and is separated in tabs for each file, making it really easy to follow. The editors have Vue.js built-in so don't be afraid to experiment. Also, you can download an archive containing all the examples from the Download button near the top of this article.

1. Navigation Menu

To kick things off we're going to build a simple navigation bar. There are a few basic components almost every Vue.js app need to have. They are:

  • The model, or in other words our app's data. In Vue.js this is simply a JavaScript object containing variables and their initial values.
  • An HTML template, the correct terminology for which is view. Here we chose what to display, add event listeners, and handle different usages for the model.
  • ViewModel - a Vue instance that binds the model and view together, enabling them to communicate with each other.

The idea behind these fancy words is that the model and the view will always stay in sync. Changing the model will instantly update the view, and vice versa. In our first example this is shown with the active variable, representing which menu item is currently selected.

HTMLJSCSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div id="main">
<!-- The navigation menu will get the value of the "active" variable as a class. -->
<!-- To stops the page from jumping when a link is clicked
we use the "prevent" modifier (short for preventDefault). -->
<nav v-bind:class="active" v-on:click.prevent>
<!-- When a link in the menu is clicked, we call the makeActive method,
defined in the JavaScript Vue instance. It will change the value of "active". -->
<a href="#" class="home" v-on:click="makeActive('home')">Home</a>
<a href="#" class="projects" v-on:click="makeActive('projects')">Projects</a>
<a href="#" class="services" v-on:click="makeActive('services')">Services</a>
<a href="#" class="contact" v-on:click="makeActive('contact')">Contact</a>
</nav>
<!-- The mustache expression will be replaced with the value of "active".
It will automatically update to reflect any changes. -->
<p>You chose <b>{{active}}</b></p>
</div>
Run

As you can see working with the library is pretty straightforward. Vue.js does a lot of the work for us and provides familiar, easy to remember syntax:

  • simple JavaScript object for all the options
  • {{double brackets}} for templating
  • v-something inline attributes for adding functionality directly in the HTML.

2. Inline Editor

In the previous example our model had only a couple of predefined values. If we want to give the users the ability to set any data, we can do two-way binding and link together an input field with a model property. When text is entered, it is automatically saved in the text_content model, which then causes the view to update.

HTMLJSCSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- v-cloak hides any un-compiled data bindings until the Vue instance is ready. -->
<!-- When the element is clicked the hideTooltp() method is called. -->
<div id="main" v-cloak v-on:click="hideTooltip" >
<!-- This is the tooltip.
v-on:clock.stop is an event handler for clicks, with a modifier that stops event propagation.
v-if makes sure the tooltip is shown only when the "showtooltip" variable is truthful -->
<div class="tooltip" v-on:click.stop v-if="show_tooltip">
<!-- v-model binds the contents of the text field with the "text_content" model.
Any changes to the text field will automatically update the value, and
all other bindings on the page that depend on it. -->
<input type="text" v-model="text_content" />
</div>
<!-- When the paragraph is clicked, call the "toggleTooltip" method and stop event propagation. -->
<!-- The mustache expression will be replaced with the value of "text_content".
It will automatically update to reflect any changes to that variable. -->
<p v-on:click.stop="toggleTooltip">{{text_content}}</p>
</div>
Run

Another thing to note in the above code is the v-if attribute . It show or hides a whole element depending on the truthfulness of a variable. You can read more about it here.

3. Order Form

This example illustrates multiple services and their total cost. Since our services are stored in an array, we can take advantage of the v-for directive to loop through all of the entries and display them. If a new element is added to the array or any of the old ones is changed, Vue.js will automatically update and show the new data.

HTMLJSCSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- v-cloak hides any un-compiled data bindings until the Vue instance is ready. -->
<form id="main" v-cloak>
<h1>Services</h1>
<ul>
<!-- Loop through the services array, assign a click handler, and set or
remove the "active" css class if needed -->
<li v-for="service in services" v-on:click="toggleActive(service)" v-bind:class="{ 'active': service.active}">
<!-- Display the name and price for every entry in the array .
Vue.js has a built in currency filter for formatting the price -->
{{service.name}} <span>{{service.price | currency}}</span>
</li>
</ul>
<div class="total">
<!-- Calculate the total price of all chosen services. Format it as currency. -->
Total: <span>{{total() | currency}}</span>
</div>
</form>
Run

To display the prices in a correct format we will have to define a simple currency filter. Filters allow us to lazily modify or filter the model data. To define a custom filter we have to use the following syntax:

// Define a custom filter called "currency". 
Vue.filter('currency', function (value) {
    return '$' + value.toFixed(2);
});

As you can see our filter is pretty straightforward - it adds a dollar sign and proper number decimals. Just like in Angular filters are applied using the | syntax - {{ some_data | filter }}.

4. Instant Search

Here we will create an app, that exhibits some of the articles on our website. The app will also have a text search field allowing us to filter which articles are displayed. All of the articles will be held in an articles array, and those articles that match the search query will be in a computed property called filteredArticles.

HTMLJSCSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<form id="main" v-cloak>
<div class="bar">
<!-- Create a binding between the searchString model and the text field -->
<input type="text" v-model="searchString" placeholder="Enter your search terms" />
</div>
<ul>
<!-- Render a li element for every entry in the computed filteredArticles array. -->
<li v-for="article in filteredArticles">
<a v-bind:href="article.url"><img v-bind:src="article.image" /></a>
<p>{{article.title}}</p>
</li>
</ul>
</form>
Run

The input field is bind to the searchString model. When text is entered the model is instantly updated and the computed filteredArticles array is generated again. This way we can create a real-time search without having to worry about rendering or setting up event listeners - Vue.js handles all that!

5. Switchable Grid

In our last example we will demonstrate a common scenario where a page has different layout modes. Just like in the previous app we will be showing a list of articles from tutorialzine.com stored in an array.

By pressing one of the buttons in the top bar you can switch between a grid layout containing large images, and a list layout with smaller images and text.

HTMLJSCSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<form id="main" v-cloak>
<div class="bar">
<!-- These two buttons switch the layout variable,
which causes the correct UL to be shown. -->
<a class="list-icon" v-bind:class="{ 'active': layout == 'list'}" v-on:click="layout = 'list'"></a>
<a class="grid-icon" v-bind:class="{ 'active': layout == 'grid'}" v-on:click="layout = 'grid'"></a>
</div>
<!-- We have two layouts. We choose which one to show depending on the "layout" binding -->
<ul v-if="layout == 'grid'" class="grid">
<!-- A view with big photos and no text -->
<li v-for="a in articles">
<a v-bind:href="a.url" target="_blank"><img v-bind:src="a.image.large" /></a>
</li>
</ul>
<ul v-if="layout == 'list'" class="list">
<!-- A compact view smaller photos and titles -->
<li v-for="a in articles">
<a v-bind:href="a.url" target="_blank"><img v-bind:src="a.image.small" /></a>
<p>{{a.title}}</p>
</li>
</ul>
</form>
Run

Conclusion

There is a lot more to Vue.js than what we've showcased in these examples. The library also offers animations, custom components and all sorts of other features. We recommend you check out the excellent official documentation which is full of information and helpful snippets.

Having troubles deciding whether Vue.js is the right library for your project? The following links will be of great help to you:

  • An official, detailed comparison with other frameworks - here.
  • TodoMVC - a website where the same app is recreated with many different frameworks.
  • Our articles where we've done similar examples using React and Angular.js.

No comments:

Post a Comment

Technology’s generational moment with generative AI: A CIO and CTO guide

 Ref:  A CIO and CTO technology guide to generative AI | McKinsey 1. Determine the company’s posture for the adoption of generative AI As us...