Vue.js Quick Start Tutorials _javascript Tips

Source: Internet
Author: User
Tags event listener

A front-end framework like ANGULARJS makes it very easy to develop powerful single-page applications, but sometimes angular this large framework is too large for our project and many features are not necessarily used. Then we need to evaluate the need to use it. If we just need to add a handful of features to a simple Web page, it's too cumbersome to use angular, the necessary installation, configuration, Routing and design controllers, and so on.

At this point we need a more lightweight solution. Vue.js is a good choice. Vue.js is a framework that focuses on the view model (Viewmodal). A view model is a bridge between the UI and the data model for data exchange, which enables bidirectional data binding between the UI and the data model. It is not a "complete framework", but a simple and flexible framework that focuses on the view layer.

Next we will use a simple memo to take you through the basics of vue.js. In order to pay more attention to vue.js itself, we design a client application based on local data, and at the end of this article we'll mention the way vue.js interacts with the backend.

Preparatory work

Let's get vue.js and bootstrap through NPM first (not necessarily, here to apply its style gallery), and enter the following on the command line:

 
 

Then create the index.html and app.js two files:

 
 

Add the following content to the index.html

<!--index.html--><!doctype html> 

The <div> tag with id "Events" is a core part of this application. Then we'll create a Vue instance for this core.

Create a Vue instance

First, let's create a Vue instance and set the "El" property of this instance to "#events". The instance is bound to a container with the ID "events".

 
 

By this step, the Vue function will be in div#events. Before adding anything else, let's add some of the necessary attributes to the Vue instance you created:

 
 

The Data property is an object that declares all the figures in the view model of our application

The Ready property is a function that is executed when the application is loaded, and usually calls other methods here to initialize the data needed for the application

The methods method defines the methods that need to be used in this application

Add content to a form

We need to enter the details of the memo in the form. We used HTML5 's native time selector to set the time for the memo content. (Note that this feature is not available in Firefox, recommended for Chrome or Safari)

 
 

We added a "v-model" instruction to the input tag and the textarea tag. Similar to angular's "Ng-model", this V-model value sets the data that is bound to the label in the view model, which is available not only here but also elsewhere in the container.

We have added a "@click" instruction to the submit button, which is abbreviated, the full name should be "V-on:click", which is to bind a click event Listener to the button, and the listener function in the @click instruction will execute when the click event is triggered. In this case, we bind the submit button to the Addevent function. We can also bind other events, write the law is the @ event name = "Listener function", such as we want to give the KeyDown event to bind a listening function f, you can write: @keydown = "F" or v-on:keydown= "F"

In this step, if you preview the page you will see the following:

Add data

We have mentioned the Addevent method before, this method is used to add new Memo data.

Now we'll define this method and add some of the necessary data

App.js. Data: {event: {name: ', Description: ', Date: '}, Events: []},//performs functions in ready properties when loading is applied ready:function () {//We need to initialize the data this.fetchevents () at the time the application is loaded;},//the method we use in the application is defined in the methods attribute methods: {//We define a method to get the data fetchevents: function () {var events = [{id:1, Name: ' Meeting ', Description: ' 9 o'clock in the morning in the 21-storey conference Room ', date: ' 2015-09-10 '}, {id:2, Name: ' Shopping ', de Scription: ' Buy a charge treasure ', Date: ' 2015-10-02 '}, {id:3, Name: ' Learning ', Description: ' Learning Vue online tutorial ', Date: ' 2016-03-11 '];//$set is a method provided by Vue to insert data into an array, and also refreshes the view when it is executed. $set (' Events ', events); (),///Insert Data addevent:function () {if (this.event.name) {This.events.push (this.event) to the event array; this.event = {name: ', Descrip tion: ', Date: '}; } }} 

In the Data property, we define an event object and an array of events that represent an array of events and events. The data is loaded when the application is loaded. If we do not define the event object, the following functionality can be implemented, but the browser will report this error:

They mean that the data you use in your application will be affected if it is not declared in the parameters. So the data we use in the application is best declared in the properties.

In the Ready property we define the Fetchevents method to get the data, in which we use the VM. $set method to add data to a view that is similar to the push method of an array, and also refreshes the view, whose arguments must be a string keypath, Represents the incoming data. The specific usage can be seen here.

Finally, in the method attribute we define the addevents approach, check whether the value of the event.name exists, and add an event to the events array if it exists. The data in the event object is then emptied, and the form is emptied.

Add a list of items

We use a list of things to list all the things:

<div class= "List-group" > <a href= "#" class= "List-group-item" v-for= "event in Events" > 

We use the v-for instruction to bulk render elements with the same DOM structure and different display contents. In this example, we add a v-for instruction to a tag that iterates through the data in the events array, and each time we iterate over the data we use the event to represent it. Elements that have been added to the V-FOR directive will use each traversal result to be repeated in child elements, and friends who have used the template engine, react, or angular may be familiar with similar usage. In our case, the contents of the H4, H5, p, and Button tabs are repeatedly displayed, and the number of loops is the length of the events array. A child element with a v-for instruction element is called a template, and the data in the template is wrapped in double braces. In this example, the data is the properties of the event object (name, date, and description).

You will notice that some of the elements of the template have been added v-if directives. This instruction plays a role in conditional rendering. The value of the v-if is a judgment condition and renders the element if the result is true, otherwise it is not rendered. Additionally, in the button element we added a click instruction that called the Deleteevent method to delete the item (given below), whose parameter $index represents the number of the element in the array that is currently traversed.

Refresh the page and we'll see that everything is listed on the right side of the page, and the new items are automatically added to the list on the right after you enter the content in the form on the left and click the "Submit" button.

Now let's define the Deleteevent method.

 
 

In this method we first ask the user if they are sure to delete the item, and if you click OK, then remove the item from the DOM by Vue the predefined $remove method.

Interacting with the back end

Like angular, the front and back ends of the Vue are detached, and the backend interaction is done through HTTP requests. There are a lot of interactive tools, you can use the familiar $.ajax, native XMLHttpRequest objects or other Third-party libraries, you can also try Vue-resource.

Here is a brief introduction to Vue-resource. Vue-resource is a plug-in designed specifically for Vue to send HTTP requests. It supports promise and URI templates and also provides tools such as interceptors (Interceptor). Or look at our example above, we change the acquisition of the matter from the server, this time we need to modify the Fetchevents method: (assuming that the backend through api/events this URL to provide matters related services, the same below)

 
 

If it succeeds, it executes the statement of the then function, still calling the $set method, except that the input parameter events become retrieved from the server.

If the addevent is modified, we need to send a POST request:

 
 

Similarly, the method of deleting a matter can be modified as follows:

 
 

Here we pass the ID of the item to the server, informing the server of the item ID to be deleted to make it easier for the server to determine which item to delete.

Conclusion

Friends who have used angular and react will find that Vue and them have many similarities: instructions similar to angular, and modular processing similar to react. However Vue and they are significantly different, it is lighter, easy to use, you do not need to be like angular to carry out complex configuration, and do not need to like react to learn new virtual DOM, JSX and so on new concepts. Therefore, if your application is not very large, you may wish to consider using Vue as your application framework.

The above is a small set to introduce the Vue.js QuickStart tutorials, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.