Vue.js component Use development instance Tutorial _javascript tips

Source: Internet
Author: User
Tags modifier

Component

A component can extend HTML elements, encapsulate reusable code, at a higher level, a component is a custom element, a vue.js compiler adds special functionality to it, and in some cases, a component can also be the form of a native HTML element, extended as an IS attribute.

Vue.js components can be understood as ViewModel classes that have predefined behavior. A component can be predefined for many options, but the core is the following:

Template (Template): The template declares the mapping relationship between the data and the DOM that is eventually presented to the user.

Initial data: The initial data state of a component. This is usually a private state for reusable components.

Accepted external parameters (props): Data is passed and shared between components through parameters. The parameter defaults to a one-way binding (from top to bottom), but can also be explicitly declared as a two-way binding.

Method (Methods): Changes to the data are generally performed within the method of the component. You can bind user input events and component methods through the v-on directive.

Life cycle hook function (lifecycle hooks): A component triggers multiple lifecycle hook functions, such as created,attached,destroyed, and so on. In these hook functions, we can encapsulate some custom logic. Compared with traditional MVC, the logic that can be understood as controller is dispersed into these hook functions.

Private resources (assets): vue.js The user-defined directives, filters, components, etc. collectively as resources. A component can declare its own private resources because it is easy to cause naming conflicts with global enrollment resources. Private resources can be invoked only by the component and its subcomponents.

In addition, the components within the same component tree can communicate through the built-in event APIs. Vue.js provides a sophisticated API for defining, reusing, and nesting components, allowing developers to use components to spell out the entire application interface as a building block.

Components greatly improve the efficiency and maintainability of the code and the reuse rate.

Working with Components

Registered

1. Create a Component Builder:

var mycomponent = vue.extend ({
//Option
})

2. Use the constructor as a component and register with Vue.component (tag,constructor):

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

3. Use the custom element <my-component> in the module of the parent instance:

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

Example:

<div id= "Example" >
<my-component></my-component>
</div>
//define
var MyComponent = Vue.extend ({
Template: ' <div>a custom component!</div> '
})
//Registration
Vue.component (' my-component ', mycomponent)
//Create root instance
new Vue ({
el: ' #example '
})

Render as:

<div id = "Example" >
<div>a custom component!</div>
</div>

The template for the component replaces the custom element, and the custom element acts only as a mount point. You can use the instance option replace to decide whether to replace.

Local registration

With the instance option components registration, you do not need to register each component globally, so that components can only be used in other components:

var child = Vue.extend ({/* ... */})
var Parent = vue.extend ({
Template: ' ... ',
components: {
//<my-c Omponent> can only be used within the parent component Template
' my-component ': Child
}
}

This encapsulation also applies to other resources, such as directives, filters, and transitions.

Register Grammar Candy

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

Component Options Issues

Most options for incoming Vue constructors can also be used in Vue.extend (), in addition to data and El, if you simply pass an object to Vue.extend () as the data option, all instances will share the same data object. So we should use a function as the data option to let this function return a new object:

var mycomponent = vue.extend ({
data:function () {return
{a:1}}}
)

Template parsing

The Vue template is a DOM template that uses the native parser of the browser, so it must be a valid HTML fragment, and some HTML elements have restrictions on what elements can be placed inside it, and the common limitations are:

A cannot contain other interactive elements (such as buttons, links)

UL and OL can only directly contain Li

Select can only contain option and Optgroup

Table can only directly include THEAD, Tbody, TFOOT, TR, caption, Col, Colgroup

TR can only contain th and TD directly

In practice, these restrictions can lead to unexpected results. Although it may work in a simple situation, you cannot rely on custom components to expand the results before the browser validates. For example

<my-select><option>...</option></my-select> is not a valid template, even if the My-select component eventually expands to <select> .... </select>.

Another result is that custom tags (including custom elements and special tags, such as <component>, <template>, <partial>) cannot be used in tags that are restricted to internal elements such as UL, select, table, etc. The custom tags placed inside these elements will be referred to the outside of the element, rendering it incorrect.

For custom elements, you should use the IS attribute:

<table>

<tr is= "my-component" ></tr>
</table>
//<template> can not be used in <table>, this should use < Tbody>,<table> can have multiple <tbody>
<table>
<tbody v-for= "item in Items" >
<tr >even row</tr>
<tr>odd row</tr>
</tbody>
</table>

Props

Passing Data using props

The scope of the component instance is isolated, and you can use props to pass the array to the subassembly, props is a field of the component data, expecting that the subassembly will be passed down from the parent component explicitly using the props option to declare props:

Vue.component (' child ', {
//Declaration props
Props: [' msg '],
///prop can be used in the template
//can be set with ' this.msg '
Template: ' <span>{{msg}}</span> '
})

Then pass it to a normal string:

<child msg= "Hello!" ></child>

Dynamic props

V-bind bind dynamically props data to the parent component, which is also transmitted to the subassembly whenever the data of the parent component changes:

<div>
<input v-model= "parentmsg" >
<child v-bind:my-message= "Parentmsg" ></child >
//<child:my-message= "parentmsg" ></child>
</div>

Props binding Type

Prop default is one-way binding, which will be passed to the subassembly when the parent component's properties change, but not in turn, in order to prevent the child component from unintentionally modifying the state of the parent component, and to force bidirectional or single binding by using the. Sync or. Once binding modifier modifier explicitly:

<!--default is one-way binding-->
<child:msg= "parentmsg" ></child>
<!--bidirectional binding-->
<child: Msg.sync= "Parentmsg" ></child>
<!--single bind-->
<child:msg.once= "Parentmsg" ></child >

If prop is an object or array, it is passed by reference. modifying it within a subassembly affects the state of the parent component, regardless of which binding type is used.

Parent-Child Component communication

Parent chain

A subassembly can access its parent component with this. $parent, and the descendants of the root instance can access it using this. $root, the parent component has an array this. $children, including all its child elements

Custom events

The Vue instance implements a custom event interface for communication in the component tree, which is independent of native DOM events and is used differently, and each Vue instance is an event trigger:

Use $on () to monitor events;

Use $emit () to trigger the event above it;

The event is distributed using $dispatch (), and the event bubbles along the parent chain;

Using the $broadcast () broadcast event, the event is transmitted downward to all descendants.

Unlike DOM events, the Vue event automatically stops bubbling after the first triggering of a callback in the bubbling process, unless the callback explicitly returns TRUE.

<!--subassembly template-->
<template id= "Child-template" >
<input v-model= "msg" >
<button v-on: Click= "Notify" >dispatch event</button>
</template>
<!--parent component Templates--> <div id=
" Events-example ">
<p>messages: {{Messages | json}}</p>
<child></child>
< /div>/
/Register subassembly
//Send out the current message
vue.component (' child ', {
template: ' #child-template ',
data : function () {return
{msg: ' Hello '}
},
methods: {
notify:function () {
if (This.msg.trim ()) {This
. $dispatch (' child-msg ', this.msg)
this.msg = '}}}}
)
//Initialize parent component
/ /push event into an array when message is received
= new Vue ({
el: ' #events-example ',
data: {
messages: []
},
When creating an instance the ' events ' option simply invokes ' $on '
events: {
' child-msg ': function (msg) {
//Event callback ' This ' is automatically bound to the instance on which it is registered 
   this.messages.push (MSG)}}}
)

Effect:

Using v-on to bind custom events

Declare the event handler where the neutron component of the template is used, and this subassembly can listen for custom events with v-on:

<child v-on:child-msg= "Handleit" ></child>

When a subassembly triggers a "child-msg" event, the parent component's Handleit method is invoked. All code that affects the state of the parent component is placed in the Handleit method of the parent component, and the child component only focuses on the triggering event.

Sub-component Index

Using V-ref to specify an index ID for the subassembly, you can access the subassembly directly

<div id= "Parent" >
<user-profile v-ref:profile></user-profile>
</div>
var Parent = new Vue ({el: ' #parent '})
//Access subassembly
var child = parent. $refs

Distributing content using slot

Content distribution: The way to mix the content of a parent component with its own template, using a special <slot> element as the slot for the original content.

Compilation scope

The contents of the parent component template are compiled within the parent component scope, and the contents of the child component template are compiled within the child component scope.

The instruction within the binding subassembly to the root node of a component:

Vue.component (' Child-component ', {
//valid, because it is within the correct scope
Template: ' <div v-show= ' Somechildproperty ' > Child</div> ',
data:function () {return
{
somechildproperty:true
}}}
)

Similarly, the distribution content is compiled within the parent component scope.

Single slot

The contents of the parent component will be discarded unless the subassembly template contains <slot>, and if the subassembly template has only one slot, the entire contents of the parent component will be inserted in the place where slot is located and replaced.

The contents of the <slot> label are treated as fallback content. The rollback content is compiled within the scope of the child component, and the fallback content is displayed when the host element is empty and there is no content for insertion.

Assume that the My-component component has the following template:

<div>
 
 

Show me if there is no distribution.

</slot>
</div>

Parent Component Template:

<my-component>
<p>this is some original content</p>
<p>this are some more original Content</p>
</my-component>

Render Result:

<div>
 
 

Named slot

<slot> elements can be configured with a special attribute named how to distribute content, multiple slot can have different names, and named slot will match elements in the content fragment that correspond to slot attributes.

You can still have an anonymous slot, which is the default slot, as a fallback slot that cannot find a matching piece of content. If there is no default slot, the content fragments that cannot find a match are discarded.

Dynamic components

Multiple components can use the same mount point, and then dynamically switch between them, using a reserved <component> element to dynamically bind to its is attribute:

New Vue ({
el: ' Body ',
data: {
currentview: ' Home '
},
components: {Home
: {/* ... *},
Posts: {/* ... */},
archive: {/* ... */}
}
)
<component:is= "CurrentView" >
<!--components in V Change--> </component> when M.currentview change

Keep-alive

Leave the switch out of the component in memory, and you can keep its state or avoid rendering it again.

<component:is= "CurrentView" keep-alive>
<!--inactive components will be cached-->
</component>

Activate hook

When the control component switch is long, the Activate hook is only used in the process of dynamic component switching or static component initialization rendering, not for manual insertion using instance methods.

Vue.component (' Activate-example ', {
activate:function (done) {
var self = this
loaddataasync (function (data) {
Self.somedata = data done
()}}
)

Transition-mode

The Transition-mode attribute is used to specify how two dynamic components transition between.

By default, a smooth transition is entered and left. This feature can specify two other modes:

In-out: The new component transitions first, and the current component transitions out after its transition is complete.

Out-in: The current component transitions first, and the new component transitions into after its transition is complete.

Example:

<!--fade out and fade in-->
<component
: is= "View"
transition= "
fade" transition-mode= "out-in" >
</component>
fade-transition {
transition:opacity. 3s ease
}
. Fade-enter,. fade-leave {
opacity:0;
}

The Vue.js component API comes from three parts--prop, events, and slot:

Prop allows the external environment to pass data to the component;

Event allows the component to trigger an action for the external environment;

Slot allows the external environment to insert content into the component's view structure.

The above is a small set for you to introduce the use of Vue.js component Development example tutorials, hope to help everyone, 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.