Vue. js learning example and vue. js learning example

Source: Internet
Author: User

Vue. js learning example and vue. js learning example

This article will share with you a summary of Vuejs and a small example of webapi calling. At the end of the year, I will try to share more with you, hoping to help you; in this chapter, I hope you will like it, and I also hope you can scan more code for support and recommendations. Thank you:

 

» Vuejs-learning hodgedge

» WebApi + Vue. js example

 

Let's share it one step at a time:

» Vuejs-learning hodgedge

First of all, if you want to learn a js framework, you must introduce the basic library of the Framework. Here I create a page and reference the library on the official website as follows: <script src = "https://unpkg.com/vue/dist/vue.js"> </script>, let's look at the basic use code of a Vue:

1 var app = new Vue({
2 
3         el: "#appVue",
4         data: {
5             msg: "the first vue",
6         }
7     });

Analyze the code. The parameter passing required by this Vue is a {} object; the el and data in it are the parameter names; el corresponds to the id of a block element on the webpage (such as the id attribute of div and table), data corresponds to the data source, and msg is the custom data source name; let's take a look at the corresponding html code and:

1 < H3 > Vue - learning hodgepodge</h3>
2 <hr / >
3 <div class="container" id="appVue">
4     <input type="text" v-model="msg" class="form-control" />
5 </div>
: it is obvious that the data MSG ("the first Vue") we initialized is reflected in the input. Take a closer look at the attribute of this input tag, which has a V-model attribute, and its corresponding value is the MSG we initialized and defined. It can be seen that the V-model plays a role in data binding. Well, let's make the data value more complex. Add an array in JSON format in the data, such as:
1 blogs: [
2            { title: "webapi" },
3            { title: "wcf" },
4            { title: "mvc" }
5]
Then we add the following HTML:
1 <ul>
2   <li class="text-left "  v-for="(blog,index) in blogs">{{index}} - {{blog.title}}</li>
3 </ul>
Refresh the page directly, as follows:
From the results, we can see that the data defined by us is directly traversed and displayed on the page, and then we can analyze the specific code. Compared with the common Li element, there is an additional V-for attribute, and there is such a syntax rule (obj, Index) in arr is similar to the writing method of for loop and has a traversal number index. With loop, you must show the value. At this time, you can see that the writing method in the sub level of Li element is {{index} - {{blog. Title}} to analyze the writing rules:
1. {{}} is the format of the output text, which contains the objects to be output
2. The parameter index corresponds to the index in V-for, and the corresponding value is the traversal sequence number, starting from 0
3. Blog.title corresponds to the blog in V-for and its corresponding custom attribute title
From the above {}} data binding writing method, we have to arouse our curiosity about her. In fact, this writing method is the same in many JS data binding frameworks (such as angularjs). Let's make a small example of adding to remember this writing method more deeply. First, add two attributes X and y to the data attribute just now:
1 data: {
2 MSG: "first Vue",
3             blogs: [
4                 { title: "webapi" },
5                 { title: "wcf" },
6                  { title: "mvc" }
7             ],
8             x: 444,
9             y: 2
10         },
Then add the following HTML code:
1  <input type="text" v-model="x" /> * <input type="text" v-model="y" /> = {{x *  y}}
The following effects are performed on the property page:
It can be seen from this that {{x * y}} allows expression, and when the X or y value in my text box is modified, this {x * y} will be automatically recalculated, which is similar to the concept of re assigning to the display box after JS calculation written by ourselves. Let's see how to define a method in Vue, here we use one of her attribute methods, and we define the following code:
1 var app = new Vue({
Two
3         el: "#appVue",
4         data: {
5 MSG: "first Vue",
6             blogs: [
7                 { title: "webapi" },
8                 { title: "wcf" },
9                  { title: "mvc" }
10             ],
11             x: 444,
12             y: 2
13         },
14         methods: {
15 showmsg: function() {17 this.msg = "I am" + this.msg;
18             }
19}
}
Then add the following HTML elements, < button v-on: Click = "showmsg" class = "BTN" > Click < / button >. Then look at the running and click the button several times:
The effect is that "I am" has been added to our V-model = "MSG" text box. The conclusion here is that the button starts from the method we defined in methods in Vue, showmsg, and then look at the attribute v-on: click on the button It is used to represent binding click events. V-on: click can be abbreviated as @ click. Because my MVC template in vs does not support this writing method, I still use v-on to bind events. Let's use her filter again. Here, we add the following filter code in Vue to define a case filter:
1 filters: {
2             toUpper: function (val, isUpper) {
3                 if (!val) { return ""; }
Four
5                 return isUpper ? val.toUpperCase() : val.toLowerCase();
6             }
7}
In order to see the effect conveniently, we modify the above text box code of V-model = "MSG" as follows:
1 <input type="text" v-model="msg" class="form-control" />{{msg|toUpper(true)}}<br />{{msg|toUpper(false)}}
We have added a {{msg| toupper (true)}} writing method in the text box. Careful friends can send the following toupper, which is the filter method we just defined, passing a parameter of true, and then look at it:
Through the comparison of filters with different parameters, we can see the effect of our filters in this example. What we should pay attention to here is that we can directly use '|' separation after msg to add our defined filters. If multiple filters use '|' addition separation by analogy, we can also use our defined toupper: function (val, There are two parameters in the isupper) method. The first parameter is the binding MSG itself. The second parameter is what we need to pass manually, which must be separated. As time is running out, we will not explain other commonly used features and properties here. Let's take a look at the following example of Vue using webapi data;
» webapi + vue.js example
First of all, the component concept provided by Vue is used here. It has two kinds of global and local (private) variables like JS variables. The code gap is not very big and the same. Here we use the local method to define a component. Let's look at the overall code first:
1  var blogApp = new Vue({
2         el: "#divBlogs",
3         data: {
4             blogs: []
5}
6         methods: {
7             getBlogs: function () {
Eight
9                 var that = this;
10                 $.getJSON("http://www.lovexins.com:1001/api/values?task=2", function (result) {
11                     if (!result) { return; }
12                     that.blogs = result;
13                 });
14             }
15         },
16         components: {
17             "div-blog": {
18                 props: ["item"],
19                 template: '<div class=" bs-callout bs-callout-danger">' +
20                                '    <h4>' +
21                                '        <a v-bind:href="item.Url" target="_blank">{{item.Title | toUpperOrLower(false)}}</a>' +
22                                '    </h4>' +
23                                '    <p>' +
24                                '        {{item.Des}}' +
25                                '    </p>' +
26                                '    <hr />' +
27                                '    <h5>' +
28 'author: < a v-bind: href = "item. Blogurl" target = "_blank" > {{item. Nickname}} < / a > release time: < code > {{item. Createtime}} < / code > recommendation: < code > {{{item. Zannum})} < / code > read: < code > {item. Readnum} < / code > comment: < code > {{item. Commitenum} < / code >'+
29                                '    </h5>' +
30                                ' </div>',
31                 filters: {
32                     toUpperOrLower: function (val, isUpper) {
33                         if (!val) { return ""; }
Thirty-four
35                         return isUpper ? val.toUpperCase() : val.toLowerCase();
36                     }
37                 }
38             }
39}
40};
The format defined here is similar to that used in the first section above, but there is an additional definition of components, which is the keyword of components. Let's analyze the code steps one by one;
1. Blogs: [] is an array of blog information defined by us
2. In the method attribute, the getblogs method uses a section of code var that = this. This is the above created var blogapp = new vue() object. She can directly use the blog data array defined in the data. Therefore, after getting the webapi data through the getjson of jQuery, she can directly assign it to the blog array bolgs
3. In the components component, a component named "div blog" is defined. The parameter name is the item defined by props. The template is the corresponding template, in which you can directly use the item to obtain the corresponding parameter value;
4. There is also a filter defined here, which is also case shifted. The writing method can be ignored. The main point is that when using filters in the local defined primary key, it is also in the format of {item. Title | to upper or lower (false)}}
Now, through the above summary, let's take a look at how to use this custom component in HTML, as shown in the following overall HTML code:
1 <div class="row" id="divBlogs">
2     <div class="col-md-12">
3 < button v-on: Click = "getblocks" class = "BTN BTN default" > query < / button >
4         <div-blog v-for="blog in blogs" v-bind:item="blog"></div-blog>
Five
6         <div style="position:fixed; right:0px; bottom:10px; width:44px; height:40px; background-color:#F8F8F8; font-weight:100; cursor:pointer;" id="toTop" onclick="toTop()">
7 < img title = "back" style = "width: 38px; height: 38px; border: 1px solid ා CCC" SRC = "http://121.42.208.152/images/top.png" >
8         </div>
9 </div>
10 </div>
The code that references the custom component is as follows: < div blog V-for = "blog in blogs" v-bind: item = "blog" > < / div blog > The div blog here corresponds to the third point summarized above. To customize the primary key name, it should be noted that if the custom component name format is like divblog (hump format), then the format we use in HTML must be div blog, separated by '-', and this detail should be paid special attention to otherwise the page will not work. OK, let's look at it in so many ways:
Here I use the interface opened by the previous blog to grab the data on the homepage of the blog Park: http://www.lovexins.com: 1001 / API / values? Task = 2, and the background is set to allow cross domain requests. If you are interested, you can use the data directly, and then send the online address of this instance: http://www.lovexins.com: 1001 / home / Vue. I hope you like it and hope you have more More "recommendations"

Related Article

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.