Let's compare vanilla JavaScript code with Vue JavaScript code.
For this example, we'll print out members of an array.
In vanilla JavaScript, this will be the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.list-item {
background: white;
color: gray;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<script>
var arr1 = ['a','b','c'];
var unorderedList = document.createElement('ul');
unorderedList.style.cssText = "background:tomato; width:
400px;height:400px";
document.body.appendChild(unorderedList);
for (var i=0; i<3; i++) {
var listItem = document.createElement('li');
listItem.className = "list-item";
unorderedList.appendChild(listItem);
listItem.innerHTML = arr1[i];
}
</script>
</body>
</html>
In this file, the focus should be on the code inside the script tags.
You can see this example in the form of a pen at this URL: https://codepen.io/AjdinImsirovic/pen/xzPdxO.
There are several things that we are doing in this code:
- We are setting array1, which will later populate the list items we will create dynamically
- We are creating a ul—an unordered list element that will wrap all our list items (all our li elements)
- We are setting the styles for our ul
- We are appending unorderedList to the body of our document
- Next, we use a for loop to create three li elements
- Still inside the for loop, we add a class to each list item
- We then append each of them to the unordered list element
- Finally, we add innerHTML to each list itemÂ
Many objections could be made to the way that this code is made. We could have used a forEach; we could have avoided adding styles the way we did and instead called the CSS from a separate file. But the biggest objection is how fragile this code is. Let's contrast this code with the same thing written in Vue.
In Vue, our code will look like this:
<!-- HTML -->
<ul>
<li v-for="entry in entries">
{{ entry.content }}
</li>
</ul>
// JS
var listExample = new Vue ({
el: "ul",
data: {
entries: [
{ content: 'a'},
{ content: 'b'},
{ content: 'c'}
]
}
})
The code for this example can be found here: https://codepen.io/AjdinImsirovic/pen/VdrbYW.
As we can see at just a simple glance, Vue's code is a lot easier to understand and reason about in comparison to the same code implemented in vanilla JavaScript.Â
The el here is the entry point for our Vue app. The data option is the actual data our Vue app will work with.Â
There's also another major benefit to this setup: once you understand how Vue works, any other project that uses Vue will simply make sense to you, which will yield increased productivity and efficiency.
The Vue way of doing things thus promotes being faster and doing more things in less time.