What is a component

Source: Internet
Author: User

What is a component: A 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 Vue.js's compiler 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.

How do I register a component?

You need to use the Vue.extend method to create a component, and then use the Vue.component method to register the component. The Vue.extend method format is as follows:

var mycomponent = vue.extend ({    //Options ...) Later in the introduction})

If you want to use this created component elsewhere, you'll need a component name:

Vue.component (' my-component ', mycomponent)

You can use this component name in an HTML tag after you name it, just like with DOM elements. Let's take a look at a complete component registration and usage example.

HTML code:

<div id= "Example" >    <my-component></my-component></div>

JS Code:

define var mycomponent = Vue.extend ({    Template: ' <div>a custom component!</div> '})//register vue.component (' My-component ', mycomponent)//Create root instance new Vue ({    el: ' #example '})

Output Result:

<div id= "Example" >    <div>a Custom Component!</div></div

Nested Components

The component itself can also contain components, and the following parent component contains a named Child-component component, but this component can only be used by the parent component:

var child = Vue.extend ({    Template: ' <div>a custom component!</div> '}); var parent = Vue.extend ({    Template: ' <div>parent Component: <child-component></child-component></div> ',    Components: {        ' child-component ': Child    }}); Vue.component ("Parent-component", parent);

The above definition process is cumbersome, and you can not call the Vue.component and Vue.extend methods every time:

Expand in one step with register vue.component (' my-component ', {Template: ' <div>a custom component!</div> '})// Local registration can also do so var Parent = Vue.extend ({components    : {        ' my-component ': {            Template: ' <div>a custom Component!</div> '}}    )

Dynamic Components

Multiple components can use the same mount point and then dynamically switch between them. Use the reserved <component> element to dynamically bind to its is attribute. The following example hangs the home, posts, and archive three components in the same Vue instance, with the feature currentview dynamic switch component display.

HTML code:

<div id= "dynamic" >    <button id= "Home" >Home</button>    <button id= "Posts" >posts</ button>    <button id= "Archive" >Archive</button>    <br>    <component:is= " CurrentView "></component></div>

JS Code:

var vue = new Vue ({    el: "#dynamic",    data: {        CurrentView: "Home"    }, Components    : {        home:{            Template: "Home"        },        posts: {            Template: "Posts"        },        archive: {            Template: "Archive"        }    }}); document.getElementById ("Home"). onclick = function () {Vue.currentview = "home";}; document.getElementById ("posts"). onclick = function () {Vue.currentview = "posts";}; document.getElementById ("archive"). onclick = function () {Vue.currentview = "archive";};

Components and V-for

<my-component v-for= "Item in Items" ></my-component>

You cannot pass data to a component because the scope of the component is independent. In order to pass data to the component, you should use props:

<my-componentv-for= "Item in Items": item= "item": index= "$index" ></my-component>

The item reason for not automatically injecting components is that this causes the component to be tightly coupled with the current v-for . Explicitly declares where the data comes from so that the component can be reused elsewhere.

In -depth response principle

When a component binds data, how does it bind to be valid, and can dynamically modify and add properties? Take a look at the following schematic introduction.

How to Track Changes: Pass a different object to the Vue instance as the option for data, Vue.js will traverse its properties and use Object.defineproperty to convert it to getter/setter. This is the ES5 feature, and all vue.js do not support IE8 or earlier versions.
Each directive/data binding in the template has a corresponding Watcher object, which records the property as dependent during the calculation. The watcher is then triggered when the dependent setter is called. The process is as follows:

Change detection problem: Vue.js cannot detect the addition or deletion of object attributes, the attribute must be on data to allow Vue.js to convert it to Getter/setter mode in order to respond. For example:

var data = {a:1};var vm = new Vue ({data:data});//' VM.A ' and ' data.a ' are now in response to Vm.b = 2//' Vm.b ' is not responding data.b = 2//' data.b ' is not a response

However, there are ways to add a property after the instance is created and make it appropriate. You can use the set (Key,value) instance method:

VM. Set (' B ', 2)//' vm.b ' and ' data.b ' are now responsive

For normal objects You can use the global method: Vue.set (object, key, value):

Vue.set (data, ' C ', 3)//' vm.c ' and ' data.c ' are now responsive

Initialize data: Although Vue.js provides dynamic addition of the corresponding property, it is recommended to declare all the corresponding properties on the data object.

Do not do this:

var vm = new Vue ({    Template: ' <div>{{msg}}</div> ')///Then add ' msg ' VM. $set (' msg ', ' hello! ')

Should do this:

var vm = new Vue ({    data: {        //with a null value ' MSG '        msg: '    },    Template: ' <div>{{msg}}</div> ') Then set ' msg ' vm.msg = ' hello! '

Component Complete case

The example below shows the modal window function, the code is relatively simple.

HTML code:

<!--implement script to define a template--><script type= "x/template" id= "Modal-template" > <!--whether the template is displayed by v-show= "Show", Transition animating Effects-<div class= "Modal-mask" v-show= "show" transition= "modal" > <div class= "modal-wrap                    Per "> <div class=" Modal-container "> <div class=" Modal-header ">                    <!--slot equals header placeholder--<slot name= "header" > Default header </slot> </div> <div class= "Modal-body" > &L t;!                    --slot equivalent to Body placeholder--<slot name= "Body" > Default body </slot> </div> <div class= "Modal-footer" > <!--Slots                    Equivalent to footer placeholder--<slot name= "footer" > Default footer            </slot>        <button class= "Modal-default-button" @click = "show = False" >OK</button> </div> </div> </div> </div></script><div id= "App" > <!--set the Vue instance feature when the button is clicked Showmo The value of the DAL is true--> <button id= "show-modal" @click = "ShowModal = True" >show modal</button> <!--modal is a custom A plug-in, plug-in feature show bound Vue instance showmodal features--<modal:show.sync= "ShowModal" > <!--Replace the contents of the slot in the modal plugin-- > 

JS Code:

Defines a plug-in with the name Modalvue.component ("modal", {    ///plugin template binding ID modal-template DOM element content template    : "#modal-template" ,    props: {        //attribute, type Boolean        show:{            Type:boolean,            required:true, Twoway:true}}    ); /Instantiate Vue, scope under ID for app element, new Vue ({    el: "#app",    data: {        ///attribute, default = False        Showmodal:false    }});

CSS code:

. modal-mask {position:fixed;    z-index:9998;    top:0;    left:0;    width:100%;    height:100%;    Background-color:rgba (0, 0, 0,. 5);    display:table; Transition:opacity. 3s ease;}.    modal-wrapper {Display:table-cell; Vertical-align:middle;}.    Modal-container {width:300px;    margin:0px Auto;    padding:20px 30px;    Background-color: #fff;    border-radius:2px;    box-shadow:0 2px 8px rgba (0, 0, 0,. 33);    Transition:all. 3s ease; Font-family:helvetica, Arial, Sans-serif;}.    Modal-header h3 {margin-top:0; Color: #42b983;}. Modal-body {margin:20px 0;}. Modal-default-button {float:right;} /** The following styles were auto-applied to elements with* v-transition= "modal" when their visiblity was toggled* by VUE.J s.** you can easily play with the modal transition by editing* these styles.*/.modal-enter,. modal-leave {opacity:0;}    . modal-enter. Modal-container,.modal-leave. Modal-container {-webkit-transform:scale (1.1); Transform: Scale (1.1);} 

Because of their own in the project has not much in-depth use of the function of the components, so their understanding of the component is not in-depth, the introduction of the relatively superficial, suddenly spray.

What is a 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.