JS Component Series--Another MVVM component: Vue (two: Building your own Vue component)

Source: Internet
Author: User
Tags new set

Read Catalogue

    • First, why components are important
    • Second, the basic knowledge of the components inside Vue
      • 1, the concept of components
      • 2. Principle of components
      • 3, the use of components
    • Third, the packaging of their own component
      • 1, using component package bootstraptable
      • 2. Package Select
      • 3. View other Vue framework source code
    • Iv. Summary

Body

Preface: The Blink of an eye from the previous JS component series--Another MVVM component: Vue (A: 30 minutes to fix the front end add and delete) has been for several months, today intends to pick it up, found a long time, Vue related technology points are unfamiliar. Over the past few months, Vue's development has been unusually rapid, but it seems to have little to do with bloggers, bloggers or honestly study their own technology it. The road to technology is long, and it's done and researched.

Original address of this article: http://www.cnblogs.com/landeanfen/p/6518679.html

Back to top one, why components are important

Two days ago, saw an article about the summary Vue Open source project, the resources are very rich, have to lament the power of the open source community. Just go in and see a few UI components, basically not native HTML usage, if you don't understand Vue's component-related concepts and see some "wacky" label notation, it might be used, but it's certainly not understandable why you can write that. For example, we casually find a name iview to see:

<i-input type= "text": value.sync= "Forminline.user" placeholder= "Username" >     <icon type= " Ios-person-outline "slot=" prepend "></Icon></i-input>

Such a piece of code would have the following effect:

Bloggers are curious, and are going to look at the origins of these "wacky" ways of writing today. Hope that through this article, let you have a kind of "Oh, the original is so, but so!" "The Feeling!

Back to top Ii. component basics inside Vue back to top 1, component concept

Official definition: Components (Component) is one of the most powerful features of Vue.js. Components can extend HTML elements to encapsulate reusable code. At a higher level, the component is a custom element, and the compiler for Vue.js adds special functionality to it. In some cases, a component can also be the form of a native HTML element, extended with the IS attribute.

Bloggers understand that the components inside Vue can be understood to be a set of independent and universally available HTML tags that are encapsulated in plain HTML tags, and we can invoke the encapsulated components using these tags in the page to pass in the appropriate parameters. Believe it at a glance by following this picture.

A new set of elements consisting of a normal HTML tag form, input, button, and label is named I-form, and this i-form is the concept of the component inside the Vue. When we use <i-form></i-form> in the page, through the Vue component rendering mechanism, in the browser can finally be displayed as a normal HTML tag form, input, button, label.

Back to top 2. Principle of components

As we know, the components inside Vue are actually collections of ordinary HTML elements. So, how does it convert these custom tags to plain HTML tags? Before introducing the principle of components, let's look at one of the simplest component instances.

<div style= "text-align:center;margin-top:200px;" id= "app" >        <!--3. Use components in Vue instances--        < b-component></b-component>    </div>    <script src= "Content/vue/dist/vue.js" ></ script>    <script type= "Text/javascript" >        //1. Creating a Component Builder        var mycomponent = vue.extend ({            Template: ' <div id= "bcomponent" > I am the content of the custom component </div> '        });        2. Register the component into Vue inside        vue.component (' b-component ', mycomponent)        new Vue ({            el: ' #app ',        });            </script>

Get results:

The whole process is not difficult to understand, mainly divided into three major steps:

    1. Defines a component constructor that declares the HTML content to be rendered by the component
    2. Register the component constructor with the Vue component system to make it a component of Vue, giving the component a name, such as B-component
    3. Use the components in the Vue instance. Since the above two steps define the Vue component, since it is the Vue component, then to use the component, you first have to have a Vue instance, and the component must be used in the instance of Vue.

Finding a diagram on the Web can clearly explain the entire rendering process of the component.

In fact sometimes for the sake of simplicity, we often merge 1, 2 steps, the code is as follows:

<div style= "text-align:center;margin-top:200px;" id= "app" >        <!--2. Use components in Vue instances--        < b-component></b-component>    </div>    <script src= "Content/vue/dist/vue.js" ></ script>    <script type= "Text/javascript" >        //1. Create a component constructor, register the component into the Vue inside        vue.component (' b-component ' , {            Template: ' <div id= ' bcomponent ' > I am the content of the custom component </div> '        } '        new Vue ({            el: ' #app ',        }) ;            </script>

The results are the same as above.

Back to top 3, component use

The above explains the definition and principle of the next component, the simple and practical component, we mainly introduce the following aspects.

(1) Scope of the component

This should not be difficult to understand, the components are divided into global components and local components, that is, you can define a global component on the page, any Vue instance above the page can be used, and for the local component, is related to the specific Vue instance, can only be used in the current Vue instance of the component. It is also important to note that the component must be used in the instance of Vue and is not valid for use outside of the Vue instance. The differences are clearly illustrated by the following example.

<body> <div style= "text-align:center;margin-top:50px;" id= "app" > <b-component></b-component > <b-component2></b-component2> </div> <div style= "text-align:center;margin-top:50px; "Id=" app2 "> <b-component></b-component> <b-component2></b-component2> </di v> <b-component></b-component> <b-component2></b-component2> <script src= "Conten T/vue/dist/vue.js "></script> <script type=" Text/javascript ">//define Components Vue.component (' B-compo            Nent ', {Template: ' <div id= ' bcomponent ' > I am a global component, any Vue instance can use </div> '} ' new Vue ({ El: ' #app ', components: {' B-component2 ': {Template: ' <div id= ' bcom        Ponent "> I am a local component that can only be used in this div of the app </div> '}}";       New Vue ({el: ' #app2 ',});     </script></body> 

Get results:

(2) Transfer value of the component

The scope of the component instance is orphaned. This means that the parent component's data cannot and should not be referenced directly within the child component's template. You can use props to pass data to sub-components. How do you understand this passage? Let's look at some examples first.

    • Static prop

Let's take a look at the following simple code

<body>    <div style= "text-align:center;margin-top:50px;" id= "app" >        <b-component componentmessage= "Hello" ></b-component>    </div>       <script src= "Content/vue/dist/vue.js" > </script>    <script type= "Text/javascript" >        vue.component (' b-component ', {            Template: ' < Div>{{componentmessage}}</div> ',            props: [' componentmessage '],        })        new Vue ({            el: ' #app '        });    </script></body>

The external values are passed into the component template by using the Props property inside the component. The final rendering to the page will be "<div> Hello </div>" Such a piece of HTML

    • Dynamic prop

In most cases, when we use the Vue instance, we typically pass in the model via the Data property, for example

New Vue ({            el: ' #app ',            data: {                name: ' Jim ', age                : ' +}        });

How will our name and age be passed to the component instance at this time?

<body>    <div style= "text-align:center;margin-top:50px;" id= "app" >        <b-component v-bind: My-name= "Name" v-bind:my-age= "age" ></b-component>    </div>    <script src= "content/vue/dist /vue.js "></script>    <script type=" Text/javascript ">        vue.component (' b-component ', {            Template: ' <div> name: {{MyName}}, Age:{{myage}}</div> ',            props: [' myName ', ' MyAge '],        })        new Vue ( {            el: ' #app ',            data: {                name: ' Jim ', age                : ' + '            }        });    </script></body>

Get results

Some points need to be explained:

    • When using label <b-component>, the name and age properties inside the Vue instance are passed into the component instance as aliases My-name, my-age through the V-bind command.
    • Why My-name, my-age into the component into the [' MyName ', ' MyAge ']? This is because the CamelCase nomenclature is used when defining prop in subcomponents. Because HTML attributes are not case-sensitive, the CamelCase prop is used for attributes that need to be kebab-case (dashes separated).
    • In many cases, the v-bind can be shortened to a colon (:), so the above code can also be written as follows: <b-component:my-name= "name": my-age= "Age" ></b-component>. The effect is the same.
    • It's disgusting here. Also, the definition of a variable in the props must use the so-called "hump-style" way to define the variables, otherwise it will kill you because of a variable name case. For example props:["MyName") This can be correct, but if props:["MyName" and so on is wrong, use myName value will be undefined. Bo Master for the first time to play this thing to find long time, novice must pay attention to, Tai Hang, Tai Hang, Tai Hang! Beware of entering!

In the encapsulated component, the props property uses a lot, and more props usage can be found in the documentation Https://vuefe.cn/v2/guide/components.html#Prop

(3) slot of the component

When working with components, we often need to pass in HTML elements to the component template in the component instance, and at this point we need to leave some placeholders (commonly known as "pits") in the template tags of the component, then pass in the tags in the specific component instance to fill in the "pits", which are also called slots in the Vue, using <slot> to solve. For developers, this is not a stranger, from the original master page to the current layout page, basically is the use of this principle.

<body> <div style= "text-align:center;margin-top:50px;" id= "app" > <b-component> <            H1 slot= "header" > here may be a page title 

Get results

The above code should not be difficult to understand, is a "dig pit" and "pits" process. Incidentally, Vue's components support the use of the <templete> mode to define the label template, which is more flexible and convenient to use.

Back to the top three, packaging their own component

The above mentioned so much, is about Vue inside component components part of the main knowledge points, and many others are not expanded to say, because this aspect of the document is also very rich, the garden inside the keepfool of the Vue components of the part of the introduction is very detailed, moreover, The Vue Chinese documentation is also available in a very detailed usage note. Next, the blogger intends to illustrate the benefits of using components to our front-end development through a few examples.

Back to top 1, use component package bootstraptable

For the project inside the table display, can be based on Vue can develop a set of their own, but to tell the truth, the project is quite large, and if you want to do well, to be compatible with a lot of table functions, from scratch to repeat the wheel is a bit too time-consuming. Most of the tables in the blogger project use the Bootstraptable component, so bloggers have been wondering if they can encapsulate a set of Vue-based bootstraptable usage. Similar encapsulation examples are not found on the web, and most of the frames that use Vue will implement their own table styles themselves. So I'm going to try it on my own, just to be familiar with the usage of component.

First create a new JS file named Vue.bootstrapTable.js. Bloggers directly paste the code out, if there is imperfect place, I hope everyone treatise.

(function ($) {    //table initialization default parameter    var defaults = {        method: ' Get ',                              toolbar: ' #toolbar ',                        striped:true,                              Cache:false,                               pagination:true,                       };    Register bootstraptable Component    vue.component (' bootstrap-table ', {        template: ' <table></table> ',        Props: {            ' Tableparam ': {type:object}        },        //component rendered before        created:function () {            //debugger;        } ,        //component rendered after        mounted:function () {            debugger;            var params = $.extend ({}, defaults, This.tableparam | | {});            This.bootstraptable = $ (this. $el). bootstraptable (params);        }    );}) (JQuery);

And then the interface above

Final Test Result:

Throughout the dozens of lines of code, the basic fact is very simple, through the component's props function to the <bootstrap-table> instance of the initialization parameters into the component template, and then after the component loading is completed, initialize the bootstraptable, Finally, an instance of bootstraptable is given to the component so that it can be called through the instance of Vue to the currently initialized Bootstraptable object through the child component.

Back to top 2, package Select

The package for select is still intended to be based on third-party components. Similarly, we create a new JS file named Vue.bootstrapSelect.js, whose code is as follows:

(function ($) {    $ ("Body"). Append (' <template id= "bootstrapselect" > ' +        ' <select class= "Selectpicker" v-if= "Mymultiple" v-bind:data-live-search= "Mysearch" multiple> ' +            ' <option v-for= "item in MyDatasource" V-bind:value= "Item.value" >{{item.text}}</option> '        + ' </select> ' +        ' <select class= ' Selectpicker "V-else v-bind:data-live-search=" Mysearch "> ' +            ' <option v-for=" item in myDataSource "V-bind: Value= "Item.value" >{{item.text}}</option> '        + ' </select> ' +    ' </template> ');    Vue.component (' Bootstrap-select ', {        template: ' #bootstrapSelect ',        props: [' mydatasource ', ' mymultiple ', ' Mysearch '],        //component rendered before        created:function () {        },        //component rendered after        mounted:function () {                   }    });}) (JQuery);

Page usage

Get results:

You can then configure multiple selections to set the initialization parameter multiple to true.

Why is there a two select tag in the template? The reason is that the multiple, because as long as the label inside the Multiple,select on the automatic multi-Select, the value of multiple set to any property is not good, this does not make an if judgment, if any better method, welcome point, greatly appreciated!

Back to top 3, view other Vue framework source code

Now look at the beginning of the article HTML

<i-input type= "text": value.sync= "Forminline.user" placeholder= "Username" >     <icon type= " Ios-person-outline "slot=" prepend "></Icon></i-input>

In conjunction with the Vue component documentation, the above is an encapsulation of the input tag.

Of course, the above is only the basis of component, the package of components have to combine a lot of other things, to understand the framework of the source code also need to learn some other knowledge, but at least through this article hope to let you understand the origin of these things.

Back to top four, summary

By the end of this article, I believe you have a general understanding of Vue's component. Next, if there is time, combine webpack to introduce some of the advanced uses of Vue.

Original source of this article: http://www.cnblogs.com/landeanfen/

Welcome to reprint, but without the author's consent, reprint article must be in the article page obvious location to the author and the original link , otherwise reserve the right to pursue legal responsibility

JS Component Family-Another MVVM component: Vue (ii: Build Your own Vue component)

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.