Front-end frameworks like AngularJS can make it very convenient for us to develop powerful single-page applications. However, sometimes large frameworks like Angular are too large for our projects and many functions may not be used. At this time, we need to evaluate the need to use it. If we only need to add a few functions to a simple web page, then using Angular will be too troublesome, and the necessary installation, configuration, writing routing, designing controllers, etc. will seem too cumbersome.
At this time, we need a more lightweight solution. Vue.js is a good choice. Vue.js is a framework that focuses on view models (ViewModal). The view model is a bridge for data communication between the UI and the data model, realizing two-way data binding between the UI and the data model. It is not a "complete framework", but a simple and flexible framework focused on view layers.
Next, we will use a simple memo application to learn about the basics of Vue.js. In order to make everyone pay more attention to Vue.js itself, we designed a client application based on local data. At the end of this article, we will mention the interaction between Vue.js and the backend.
Preparation
Let's get Vue.js and Bootstrap through npm first (not necessary, here is to apply its style library), and enter the following in the command line:
npm install vue bootstrap
Then create two files:
touch index.html app.js
Also add the following content to index.html
<!-- index.html --><!doctype html><html><head> <meta charset="utf-8"> <title>Vue</title> <!-- CSS --> <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"></head><body> <!-- Navigation bar--> <nav> <div> <a><i></i> Vue Memo</a> </div> </nav> <!-- Main parts of the application--> <div id="events"> <!--Add a form--> <div> <div> <h3>Add an Event</h3> </div> <div> </div> </div> </div> <!―Displaying the content of the memo--> <div> <div> </div> </div> </div> <!-- JS --> <script src="node_modules/vue/dist/vue.js"></script> <script src="app.js"></script></body></html>
The <div> tag with ID "events" is the core part of this application. After that we will create a Vue instance for this core part.
Create a Vue instance
First, let's create a Vue instance and set the "el" attribute of this instance to "#events". In this way, the instance will be bound to a container with the ID "events".
// app.jsnew Vue({// and container binding el with ID "events": '#events'});At this point, Vue's function will take effect in div#events. Before adding other content, let's add some necessary properties to the created Vue instance:
// app.js new Vue({ //The container binding el with the ID of "events": '#events', // In the data attribute, we define the data that interacts with the web page data: {}, // When the application is loaded, the function in the ready attribute will be executed. ready: function() {}, // The methods we use in the application will define methods: {}} in the methods: {}});The data attribute is an object that declares all data in the view model of our application.
The ready attribute is a function that will be executed when the application is loaded. Usually, other methods are called here to initialize the data required by the application.
The methods method defines the methods that need to be used in this application
Add content to form
We need to enter the details of the memo in the form. We used HTML5's native time selector to set the time of the memo content. (Note that this function is not applicable in Firefox browser, it is recommended to use Chrome or Safari)
<div> <input placeholder="Event Name" v-model="event.name"> </div> <div> <textarea placeholder="Event Description" v-model="event.description"></textarea> </div> <div> <input type="date" placeholder="Date" v-model="event.date"> </div> <button @click="addEvent">Submit</button></div>
We added a "v-model" directive to the input tag and textarea tag. Similar to Angular's "ng-model", the value of this v-model specifies the data bound to this tag in the view model. This data is not only available here, but also elsewhere in the container.
We added a "@click" instruction to the submit button. This instruction is abbreviated and the full name should be "v-on:click". Its function is to bind a listener for click events to this button. When the click event is triggered, the listener function in the @click instruction will be executed. In this example, we bind the addEvent function to the submit button. We can also bind other events, and the writing rule is @event name = "listening function". If we want to bind a listener function f to the keydown event, we can write this: @keydown="f" or v-on:keydown="f"
At this point, if you preview the web page, you will see the following content:
Add data
We have mentioned the addEvent method before, which is used to add new memo data.
Now we will define this method and add some necessary data
// app.js ... data: { event: { name: '', description: '', date: '' }, events: []},// The function in the ready attribute will be executed when the application is loaded is ready: function() { // When the application is loaded, we need to initialize the data this.fetchEvents();},// The methods we use in the application will define methods in the methods attribute: { // We define a method to obtain data fetchEvents: function() { var events = [{ id: 1, name: 'Have a meeting', description: '9 am in the 21st floor conference room', date: '2015-09-10' }, { id: 2, name: 'Shopping', description: 'Buy a power bank', date: '2015-10-02' }, { id: 3, name: 'Learn', description: 'Learn tutorials on Vue', date: '2016-03-11' } ];// $set is a method provided by Vue to insert data into an array. The view will be refreshed when executing it this.$set('events', events); }, // Insert data into an array of events addEvent: function() { if(this.event.name) { this.events.push(this.event); this.event = { name: '', description: '', date: '' }; } }}In the data property, we define an event object and an event array, representing the events and the event array respectively. This data will be loaded when the application is loaded. If we do not predefined event objects, although subsequent functions can be implemented, the browser will report this error:
They mean that if the data you use in your application is not declared in the data attribute, the performance of the application will be affected. Therefore, the data we use in our application is best declared in the data attribute.
In the ready property we define the fetchEvents method to get data. In this method we add data to the view through the vm.$set method. Its function is similar to the push method of an array, and it also refreshes the view. The parameter of this method must be a string keypath, representing the incoming data. For specific usage, please refer to here.
Finally, in the method property we define the addEvents method to check whether the value of event.name exists, and if so, add event to the events array. After that, the data in the event object will be cleared, and the form will be cleared as well.
Add a list of items
We use a list of things to list all the things:
<div> <a href="#" v-for="event in events"> <h4> <i></i> {{ event.name }} </h4> <h5> <i v-if="event.date"></i> {{ event.date }} </h5> <p v-if="event.description">{{ event.description }}</p> <button @click="deleteEvent($index)">Delete</button> </a></div>We use the v-for directive to batch render elements with the same DOM structure and different display content. In this example, we add a v-for directive to a tag, which will traverse the data in the events array, and we represent each traversal data with event. Elements with the v-for directive added will apply the results of each traversal in child elements and display them repeatedly. Friends who have used the template engine, React or Angular may be more familiar with similar usage. In our example, the contents of h4, h5, p and button tags will be displayed repeatedly, and the number of loops is the length of the events array. Children with v-for directive elements are called templates, and the data in the template is wrapped in double braces. In this example, the data is the various properties of the event object (name, date, and description).
You will notice that some of the elements of the template have added v-if directives. This instruction acts as conditional rendering. The value of v-if is a judgment condition. If the result is true, the element will be rendered, otherwise it will not be rendered. In addition, we added a click instruction to the button element, and called the deleteEvent method to delete the matter (the specific definition will be given below). The parameter $index represents the number of the currently traversed element in the array.
Refresh the page and we will find that all the items will be listed on the right side of the page. After entering the content in the form on the left and clicking the "Submit" button, new items will be automatically added to the list on the right.
Let's define the deleteEvent method
deleteEvent: function (index) { if (confirm("Are you sure you want to delete this event?")) { // $remove is a Vue convenience method similar to splice this.events.$remove(index); } }In this method, we first ask the user whether he is sure to delete the item. If you click "OK", then the item will be deleted from the DOM through the predefined $remove method of Vue.
Interaction with the backend
Like Angular, Vue's front-end and back-end are separated, and the interaction with the back-end is completed through HTTP requests. There are many interactive tools, you can use the familiar $.ajax, native XMLHttpRequest object or other third-party libraries, or try vue-resource.
Here is a brief introduction to vue-resource. vue-resource is a plug-in designed specifically for Vue for sending HTTP requests. It supports Promise and URI templates, and also provides tools like Interceptor. Let’s look at our example above. We change the acquisition of matters to obtaining them from the server. At this time, we need to modify the fetchEvents method: (Suppose the backend provides services related to matters through the url of API/events, the same below)
fetchEvents:function(){ this.$http.get('api/events').then(function(events) { this.$set('events', events); }).catch(function(error) { console.log(error); });}If the acquisition is successful, then the statement of the then function will be executed, and the $set method is still called, but the input parameter events becomes retrieved from the server.
If we modify the addEvent, we need to send a POST request:
addEvent: function(){ this.$http.post('api/events', this.event) .then(function (response) { this.events.push(this.event); console.log("Event added!"); }) .catch(function (error) { console.log(error); });}Similarly, the method of deleting matters can be modified as follows:
deleteEvent:function(index){ this.$http.delete('api/events/' + event.id) .then(function (response) { this.events.$remove(index); }) .catch(function (error) { console.log(error); });}Here we pass the id of the matter to the server to tell the server to delete the id of the matter to facilitate the server to determine which matter to delete.
Conclusion
Friends who have used Angular and React will find that Vue and they are all similar: instructions similar to Angular, modular processing similar to React. However, Vue is obviously different from them. It is lighter and easy to use. You don’t need to make complicated configurations like Angular, nor do you need to learn new concepts such as new virtual DOM, JSX, etc. like React. Therefore, if your application is not very large, you might as well consider using Vue as your application framework.
The above is the quick introduction tutorial for Vue.js introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!