New JavaScript frameworks and libraries are released every month. However, when we look at Web Development, we see that three of them stand out: Vue, Angular, and React. It's very likely that you've heard of at least one of them.
In this article, we will specifically talk about Vue JS, discussing its purpose and also creating our first example with this technology. Launched in 2013 by Evan You, it is today one of the most well-known open-source projects in the Development world.
Purpose and advantages of Vue JS
Vue JS aims to help us create Web pages, significantly increasing our productivity and allowing us to perform repetitive tasks in less time and with fewer lines of code.
In addition, Vue JS is very useful for helping us manipulate the information on our page. Since it is a reactive framework, Vue allows us to create attributes in its instance and manipulate them anywhere in our HTML page.
Being very simple, Vue JS is considered by many developers to be the easiest framework to learn among the three main ones we mentioned at the beginning of the article.
Even starting a Vue project is very simple, as it can be added to our HTML code via a CDN. Quite practical, don't you think?
What do you think about creating an example using Vue JS and analyzing some of its concepts? Let's go!
First project with Vue JS
In this article, we will create a User Management system using Vue JS. This project will include a registration form and a listing of users. Its initial layout is as follows:
When registering a new user, they should be added to the user list and have the option to be deleted or edited, like this:
Imagine having to do this with Vanilla JS (plain JavaScript). It could be quite a hassle, right? Let's add Vue JS to this application and understand how it can help us.
Implementing Vue JS into the project
A very important initial concept is the following: to add Vue JS to our application, we need to create a main tag, which will be where Vue can execute its functions. We can say that this HTML element will be like the “operational boundaries” of Vue on our page.
So, let's add a The next step is to add Vue to our code. We will do this through a CDN, using the tag: With this simple line of code, we can implement the Vue script in our project and already access its features. To start Vue, we need to create another tag, which will be below the first one, and will create a new instance of the Vue object, like this: This brings us to another important concept: Vue operates through an object that we will inform to its instance. This object will contain all the options necessary for the proper functioning of this framework. An important first parameter is the HTML element that will be affected by Vue's functionalities. At this moment, we will inform the id of the tag we created earlier to a parameter called “el”. The code will look like this: Note that we inform the id using the # (hashtag), through CSS3 selectors. As we have already mentioned, Vue helps us define and manipulate the data on our page. For this, it uses another attribute of its instance. We are talking about the “data” parameter, which will store our data. Since we are working with User Management, we will create an attribute called “users”, which will initially have an empty array as its value, like this: Based on this attribute, we will be able to create all the functionalities of our page. Remember also that Vue is a reactive framework. Thus, if we change the value of this attribute, that change will be reflected in all locations where it is defined on our page. Now let's configure the creation of a new user through the registration form. To do this, we will learn two more fundamental concepts of Vue. Directives are a resource of Vue that allows us to change the default behavior of an HTML element. We can say that through them it is possible to add Vue functionalities to specific tags in our HTML document. All directives have the prefix “v-”, making it clear that they are specific resources of Vue. With directives, we can define events, loops, or even the well-known two-way data binding in elements. We will use them to define the “submit” event in our form. For this, we will use the v-on directive, used specifically for events. Additionally, we will use the .prevent modifier, which will execute the preventDefault() method, disabling the browser's default behavior on the “submit” event, which would be to refresh the page. Our code will look like this: Note that directives are very similar to HTML attributes, specified in the opening tag of elements. We also need to store the value of the username that will be created through our form. To do this, we will create another attribute in our Vue instance. We can call it “newUser” and define that initially it will hold an empty string as its value, like this: Now we need to resolve a small issue: it is necessary for the username defined in the tag to be assigned to this new attribute so that we can retrieve this information when saving the data. How can we do this? We would need a very complex code for that. The good news is that Vue already provides us with this functionality through a directive called v-model. It is responsible for defining two-way data binding in HTML elements. It is mainly used in form elements. Let's define it in our tag, informing the attribute “newUser” as its value: The next step is to actually configure the function that will be executed when we submit the form. This brings us to the next concept of Vue. The functions we create within the Vue instance are called methods. They are responsible for executing any type of action within our application, such as submitting a form, which is the case of our current project. To create a method, we need to inform it within the methods parameter in the Vue instance. Let's create a method called addUser(), which will be executed when we submit the form: Note that the methods parameter is on the same level as the data parameter. We should never inform one inside the other, as our code will not work in that case. Now that we have created the method, we need to call it in our form tag, along with the v-on directive. This part of our code will look like this: Excellent. However, we need to define what our method will actually execute, as it is currently empty. Since we are working with an array of users, we will execute the push() method on our users attribute, specifying the new user data. To reference an attribute within the Vue instance, we can use this. Thus, our method will look like this: Explaining: we inform our users array of a new object that will contain the id and name of the user. For the name, we call the “newUser” attribute, which will have its value defined by the tag. We define the user id value as the number of users plus one. Thus, the id will be numeric and will automatically increment as we create new users. To test if our code is working up to this point, let's add a console.log() in this method: Let's test the registration of our first user: Upon clicking the “Register” button, we see the following result in the console: We can see that the user's information has been correctly added to our Vue instance, which is excellent! However, the information of this new user is still not being listed on the page. Let's implement this functionality now. To list the users, we will need to perform a loop over the array in our Vue instance. We also have a directive that helps us achieve that: the v-for directive. It expects as value the variable where it will execute the for and also the name that this variable will use in each iteration. We will add this directive to the tag. Our HTML code will look like this: Note that we specify the variable “users”, in plural, which is the attribute we created in our Vue instance, and defined that in each iteration we will use the variable “user”, in singular. Inside this tag, we will define a new element, which will contain the value of each user's name. This information is contained in the user.name variable and we will set it in the value attribute of the form tag. However, an HTML attribute by default cannot interpret the value of a variable, only strings. To resolve this issue, we will use the v-bind directive. It serves to define the value of variables to HTML attributes. Our tag will look like this: While we talk about the v-bind directive, we will also use it on the tag. We will do this because it is good practice to define the key attribute on tags where we perform loops. Vue's documentation always suggests doing this. In this case, we will define the key of each list tag as the value of the user.id variable: If you wish, you can use the shorthand for the v-bind directive, which involves only specifying a colon, that is, :key. Now, if we execute another test in our project, we will see the following result: Now our registered user was correctly added to our list tag. Just one important detail: all this was done without having to reload the page or make an external request. Vue JS did this for us automatically through its reactivity. The next function we will implement is to edit a user. To edit a user's data, we will execute a new method called setUser() when we change the value of the tag. In other words, it will not be necessary to click a button, but only change the value of this information and click outside the element. Amazing, right? For this, we will need to manipulate the “change” event of the tag. We will again use the v-on directive, like this: Note that we inform two parameters for the setUser() method. 1) We inform a variable called $event.target.value. This variable contains the value of the form element itself, that is, the new value defined at the time of change. 2) We inform the variable user.id, which will help us find the correct user to make the change. Now we really need to create the setUser() method in the Vue instance. This method will have the following structure: Explaining: this method will execute the map() method on our users array, applying a function to all its items. We perform a check within this function, asking through an if() statement if the user in the array has the same id that we informed to the setUser() method. If this condition is met, we change that user's name information to the new name provided to the method. Note that this method was created purely in JavaScript, using another array method. Also, note that since this method is a function, we created its name and already specified the parentheses of the function without needing to specify the reserved word function. At this moment, if we change the user's name in the HTML element, this value will be changed not only on our page but also in the attribute of the Vue instance. This will help us a lot when we connect this application to an API, for example. Finally, we need to create the method that will perform user deletion. The delete method will be called removeUser(). It will expect as parameter the id of the user to be deleted. We will call this method in the delete button tag. It will be executed when clicking the button. The code will look like this: Once again, we made use of the v-on directive. If you wish, you can use the shorthand for this directive, represented by the @, i.e., @click. We are getting good at using directives ?. Now let's create the method in our Vue instance. It will look like this: Explaining: we made use of another array method. We used the filter() method, which returns all the items in the array that satisfy a specific condition. We defined that only the items with an id different from the one informed by the method will be returned, which will effectively delete the user with the id given as a parameter. Array methods are indeed very interesting and can help us in certain specific situations, but we can talk more about that in another article focused solely on them. At this moment, if we create more than one user on our page, they will be listed correctly: However, if we click the delete button, the user will be automatically removed from the page: With that, we come to the end of our first CRUD using Vue. If you wish, you can check the complete code of this project on our GitHub. Vue JS is indeed a very simple framework to learn, but it remains very powerful at the same time. Furthermore, it is always receiving updates and improvements. For instance, we recently talked about the news in the newly released version 3 of Vue. You can check this article by clicking here. Additionally, if you want to know all of Vue's features, you can access our Complete Vue JS Course, where we cover all the concepts of this framework in more than 135 lessons with supporting material for each concept. See you in the next article, until then :)<div id="root">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.min.js"></script>
<script>
new Vue()
</script>
new Vue({
el: '#root'
})
Adding data to the page
new Vue({
el: '#root',
data: {
users: []
}
})
Directives
<form v-on:submit.prevent>
data: {
users: [],
newUser: ''
}
<input type="text" v-model="newUser">
Methods
new Vue({
el: '#root',
data: {
users: [],
newUser: ''
},
methods: {
addUser: function() {
}
}
})
<form v-on:submit.prevent="addUser">
methods: {
addUser: function() {
this.users.push({
id: (this.users.length + 1),
name: this.newUser
})
}
}
console.log(this.users);
Listing registered users
<li v-for="user in users">
</li>
<input type="text" v-bind:value="user.name">
<li v-for="user in users" v-bind:key="user.id">
Editing a user
<input type="text" v-bind:value="user.name" v-on:change="setUser($event.target.value, user.id)">
setUser(newName, id) {
this.users.map(user => {
if (user.id == id) {
user[name] = newName;
}
});
}
Removing a user
<button class="user-delete" v-on:click="removeUser(user.id)">Delete</button>
removeUser(id) {
this.users = this.users.filter(user => {
return (user.id != id);
})
}