Tutorial on using Vue. js components as a Development Instance

Source: Internet
Author: User
Tags root access
The Vue. js component uses the Development Instance tutorial component.

Components can expand HTML elements and encapsulate reusable code. at a high level, components are custom elements and vue. the js compiler adds special functions for it. In some cases, components can also be in the form of native HTML elements and can be extended with the is feature.

The Vue. js component can be understood as a ViewModel class with predefined behavior. A component can predefine many options, but the core is the following:

Template: The template declares the ing between the data and the DOM that is finally presented to the user.

Initial data: the initial data status of a component. This is usually a private State for reusable components.

Accepted external parameters (props): data is transmitted and shared between components through parameters. By default, the parameter is one-way binding (from top to bottom), but it can also be explicitly declared as two-way binding.

Method (methods): data modification operations are generally performed in the component method. You can bind user input events and component methods using the v-on command.

Lifecycle hooks: A component triggers multiple lifecycle hook functions, such as created, attached, and destroyed. In these hook functions, we can encapsulate some custom logic. Compared with traditional MVC, the logic of Controller is dispersed into these hook functions.

Private resources (assets): Custom commands, filters, and components are collectively referred to as resources in Vue. js. A component can declare its own private resources. Private resources can only be called by this component and its child components.

In addition, components in the same component tree can communicate with each other through the built-in event API. Vue. js provides a complete set of APIS for defining, reusing, and nesting components, allowing developers to use components to spell out the entire application interface like building blocks.

The component greatly improves code efficiency, maintainability, and reuse rate.

Use Components

Register

1. Create a component constructor:

Var MyComponent = Vue. extend ({// option })

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

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

3. Use custom elements in the parent instance Module Format:

Example:

// Define var MyComponent = Vue. extend ({template :'

A custom component!

'}) // Register Vue. component ('My-component', MyComponent) // create the root instance new Vue ({el:' # example '})

Rendering:

A custom component!

The template of the component replaces the custom element. The custom element serves only as a mount point. You can use the instance option replace to determine whether to replace.

Partial Registration

Use the instance option components for registration. You do not need to register each component globally, so that the component can only be used in other components:

Var Child = Vue. extend ({/*... */}) var Parent = Vue. extend ({template: '...', components :{//
 
  
Can only be used in the parent component template 'my-component': Child }})
 

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

Register syntactic sugar

// Expand and register Vue. component ('My-component', {template: 'In one step :'

A custom component!

'}) // You can also do this for local registration var Parent = Vue. extend ({components: {'my-component': {template :'

A custom component!

'}}})

Component options

Most of the input Vue constructor options can also be used in Vue. in extend (), in addition to data and el, if you simply pass an object as a data option to Vue. extend (), then all instances will share the same data object, so we should use a function as the data option, 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 browser's native parser, so it must be a valid HTML segment. Some HTML elements have restrictions on what elements can be placed in it, common restrictions include:

A cannot contain other interaction elements (such as buttons and links)

Ul and ol can only directly contain li

Select can only contain option and optgroup

Table can only contain thead, tbody, tfoot, tr, caption, col, colgroup

Tr can only directly contain th and td

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

... Not a valid template, even if the my-select component is expanded....

Another result is that custom tags (including custom elements and special tags, such , , ) Cannot be used in ul, select, table, and other labels with restrictions on internal elements. Custom labels placed inside these elements will be outside the mentioned elements, so rendering is incorrect.

The is feature should be used for custom elements:

 
// Cannot be used . ,
There can be multiple
Even row Odd row

Props

Use props to transmit data

The scope of the component instance is isolated. You can use props to pass the array to the child component. props is a field of the component data and is expected to be passed down from the parent component, the sub-component must explicitly declare props with the props option:

Vue. component ('child ', {// declare propsprops: ['msg'], // prop can be used in the template // you can use 'this. msg 'set template: '{msg }}'})

Then input a common string to it:

  

Dynamic props

Bind a dynamic props to the data of the parent component with v-bind. Whenever the data of the parent component changes, it is also transmitted to the child component:

//

Props binding type

By default, prop is a one-way binding. When the attributes of the parent component change, it is transmitted to the child component, but in turn it does not. This is used to prevent the child component from accidentally modifying the status of the parent component. sync or. the once binding modifier explicitly forces two-way or one-time binding:

  
  
  
  
  
  

If prop is an object or array, it is passed by reference. Modifying it within a child component affects the status of the parent component, no matter which binding type is used.

Parent-Child component communication

Parent chain

Sub-components can use this. $ parent accesses its parent component. The root instance descendant can use this. $ root access it. The parent component has an array this. $ children, which contains all its child elements

Custom events

The Vue instance implements a Custom Event interface for communication in the component tree. This event system is independent of the native DOM Event and has different usage. Each Vue instance is an event trigger:

Use $ on () to listen to events;

Use $ emit () to trigger an event on it;

Use $ dispatch () to dispatch events, which bubble along the parent chain;

Broadcast events with $ broadcast (), which are passed down to all future generations.

Unlike DOM events, Vue events automatically stop bubbling after the callback is triggered for the first time during the bubble process, unless the callback explicitly returns true.

  
  
   
   Dispatch Event
  
  

Messages: {messages | json }}

// Register the sub-component // dispatch the current message to Vue. component ('child ', {template:' # child-template', data: function () {return {msg: 'hello'}, methods: {policy: function () {if (this. msg. trim () {this. $ dispatch ('child-msg ', this. msg) this. msg = ''}}}) // initialize the parent component // push the event into an array var parent = new Vue ({el: '# events-example', data: {messages: []}, // when creating an instance, the 'events' option simply calls '$ on' events: {'child-msg ': function (msg) {// The 'it' in the Event Callback is automatically bound to the instance registered with this. messages. push (msg )}}})

Effect:

Use v-on to bind custom events

Declare the event processor where the subcomponent in the template is used. Therefore, the subcomponent can use v-on to listen for custom events:

When the child component triggers the "child-msg" event, the handleIt method of the parent component is called. All codes that affect the status of the parent component are placed in the handleIt method of the parent component. Child components only focus on trigger events.

Sub-component index

Use v-ref to specify an index ID for the sub-component. You can directly access the sub-component.

Var parent = new Vue ({el: '# parent'}) // access the sub-component var child = parent. $ refs. profile

Distribute content using Slot

Content Delivery: the content of the parent component is mixed with the template of the Child component. The element is used as the slot of the original content.

Compilation Scope

The content of the parent component template is compiled within the parent component scope. The content of the Child component template is compiled within the child component scope.

Bind the commands in the child component to the root node of a component:

Vue. component ('child-component ', {// valid, because the template is in the correct scope :'

Child

', Data: function () {return {someChildProperty: true }}})

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

Single slot

The content of the parent component will be discarded unless the child component template contains If the sub-component template has only one non-feature slot, the entire content of the parent component will be inserted to the place where the slot is located and replaced with it.

The tag content is considered as the rollback content. The rollback content is compiled within the scope of the Child component. This rollback content is displayed when the host element is empty and there is no content for insertion.

Assume that the my-component has the following template:

This is my component!

If no content is distributed, it displays me.

Parent component template:

  
   

This is some original content

This is some more original content

Rendering result:

This is my component!

This is some original content

This is some more original content

Named slot

The element can use a special feature name to configure how to distribute content. Multiple slots can have different names. The named slot matches the content fragment with the corresponding slot features.

There can still be an anonymous slot, which is the default slot and serves as a slot for rollback where Matching content fragments cannot be found. If no default slot exists, the content fragments that cannot be found will be discarded.

Dynamic Components

Multiple components can use the same mount point, and then dynamically switch between them, using the reserved Element, dynamically bound to its is feature:

New Vue ({el: 'body', data: {currentView: 'home'}, components: {home :{/*... */}, posts :{/*... */}, archive :{/*... */}}})
  
   
  Keep-alive

Keep the switched component in the memory to retain its status or avoid re-rendering.



Activate hook

Control the duration of component switching. The activate hook only applies to the dynamic component switching or static component initialization rendering process, and does not apply to the manual insertion process using the instance method.

Vue.component('activate-example', {activate: function (done) {var self = thisloadDataAsync(function (data) {self.someData = datadone()})}})

Transition-mode

The transition-mode feature is used to specify how two dynamic components are transitioned.

By default, the smooth transition from entry to exit is performed. This feature can specify two other modes:

In-out: the new component enters the transition first. After the transition is completed, the current component is transitioned out.

Out-in: the current component is transitioned out first, and the new component enters after the transition is completed.

Example:

  
  
   
. Fade-transition {transition: opacity. 3 s success;}. fade-enter,. fade-leave {opacity: 0 ;}
  

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

Prop allows external environments to transmit data to components;

The event allows the component to trigger the action of the external environment;

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

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.