Chapter 1. Vue.js: The Basics
As explained in the preface, Vue.js is the library at the heart of an ecosystem that allows us to create powerful client-side applications. We don’t have to use the whole ecosystem just to build a website, though, so we’ll start by looking at Vue by itself.
Why Vue.js?
Without a framework, we’d end up with a mess of unmaintainable code, the vast majority of which would be dealing with stuff that the framework abstracts away from us. Take the following two code examples, both of which download a list of items from an Ajax resource and display them on the page. The first one is powered by jQuery, while the second one is using Vue.
Using jQuery, we download the items, select the ul element, and then if there are items, we iterate through them, manually creating a list element, adding the is-blue class if wanted, and setting the text to be the item. Finally, we append it to the ul element:
<ulclass="js-items"></ul><script>$(function(){$.get('https://example.com/items.json').then(function(data){var$itemsUl=$('.js-items');if(!data.items.length){var$noItems=$('li');$noItems.text('Sorry, there are no items.');$itemsUl.append($noItems);}else{data.items.forEach(function(item){var$newItem=$('li');$newItem.text(item);if(item.includes('blue')){$newItem.addClass('is-blue');}$itemsUl.append($newItem);});}});});</script>
This is what the code does:
-
It makes an Ajax request using
$.get(). -
It selects the element matching ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access