Play the Vue.js component in minutes _javascript tips

Source: Internet
Author: User
Tags extend

Introduction to Components

Component systems are an important concept of vue.js, which provides an abstraction that allows us to build large applications using stand-alone reusable widgets, and any type of application interface can be abstracted as a component tree:


So what is a component?
components can extend HTML elements, encapsulate reusable HTML code, and we can view components as custom HTML elements.

Creation and registration of components

Basic Steps
The use of Vue.js components has 3 steps: Creating component constructors, registering components, and using components.


The following code illustrates these 3 steps:

<! DOCTYPE html>
 
 

The results of the operation are as follows:


As you can see, there is no difference between using components and using plain HTML elements.

Understanding the creation and registration of components

We use the following steps to understand the creation and registration of components:
1. Vue.extend () is an extension of the Vue constructor, and the call to Vue.extend () creates a component constructor instead of a specific component instance.
2. The Vue.extend () constructor has an option object, and the template property of the option object is used to define the HTML that the component will render.
3. When you register a component with Vue.component (), you need to provide 2 parameters, the label of the component at the 1th parameter, and the 2nd parameter is the Component Builder.
4. The Vue.component () method calls the Component Builder internally to create a component instance.
5. The component should be mounted to a Vue instance, otherwise it will not take effect.

Note that in the 5th, the following code uses the my-component tag in 3 places, but only the my-component tags under #app1 and #app2 play a role.

<! DOCTYPE html>
 
 

Global registration and local registration

When you call Vue.component () to register a component, the registration of the component is global, which means that the component can be used under any Vue example.
If you do not need global registration, or if you want components to be used in other components, you can implement local registration with the Components property of the option object.

The example above can be changed to a local registration method:

<! DOCTYPE html>
 
 

If you do this, the browser prompts you with an error:

Parent component and Child component

We can define and use other components in an assembly, which makes up the relationship between parent and child components.

<! DOCTYPE html>
 
 

The results of this code run as follows:


Let's take a few steps to understand this code:

Let's take a few steps to understand this code:

var child = Vue.extend (...) Defines a child Component Builder
var Parent = vue.extend (...) Defines a parent Component Builder
components: {' child-component ': child}, registers the child component with the parent component and sets the label of the child component to child-component.
Template: ' <p>this is a Parent component</p><child-component></child-component> ', Use the child component as a label within the parent component.
vue.component (' parent-component ', parent) Global Register Parent component
Use tags in the page to render the contents of the parent component, while the contents of the child component are rendered


The child component is registered in the parent component and can only be used in the parent component, specifically, the subassembly can only be used in the parent component's template.

Please note that the following two seed components are used incorrectly:

1. Use as a child tag in the parent component

<div id= "App" >
 <parent-component>
 <child-component></child-component>
 </ Parent-component>
</div>

Why is this way ineffective? Because when a child component is registered to a parent component, Vue.js compiles the template for the parent component, and the contents of the template determine the HTML that the parent component will render.

Parent-component is equivalent to running, some of its child tags will only be used as normal HTML to execute, Child-component is not a standard HTML tags, will be directly ignored by the browser.

2. Using subcomponents outside the parent component label

<div id= "App" >
 <parent-component>
 </parent-component>
 <child-component>
 </child-component>
</div>

Run this code, the browser prompts the following error

Component Registration Syntax Candy

The way the above components are registered is somewhat cumbersome, vue.js to simplify the process by providing a register of syntactic sugars.

Create and register components directly using Vue.component ():

Global registration, MY-COMPONENT1 is the label name
vue.component (' My-component1 ', {
 Template: ' <div>this is the Component!</div> '
})

var vm1 = new Vue ({
 el: ' #app1 '
})

The 1th parameter of Vue.component () is the label name, and the 2nd parameter is an option object that uses the template property of the option object to define the component template.
In this way, Vue automatically calls Vue.extend () behind the scenes.

Implement local registration in the Components property of an Option object:

var vm2 = new Vue ({
 el: ' #app2 ',
 components: {
 //local registration, My-component2 is label name
 ' My-component2 ': {
  Template: ' <div>this is the second component!</div> '
 },
 //local registration, MY-COMPONENT3 is the label name
 ' My-component3 ': {
  Template: ' <div>this is the third Component!</div> '}}}


Use a script or template label

Although syntactic sugars simplify component registration, stitching HTML elements in the template option is cumbersome, leading to high coupling between HTML and JavaScript.
Thankfully, Vue.js provides two ways to isolate HTML templates that are defined in JavaScript

Using the script label

<! DOCTYPE html>
 
 

The template option is now no longer an HTML element, but rather a id,vue.js to find the corresponding element based on that ID and then compile the HTML within that element as a template.


Note: When using the script label, type is specified as Text/x-template, which is intended to tell the browser that this is not a JS script, and the browser ignores the content defined in the script label when parsing the HTML document.

using the template label

If you use the Template> label, you do not need to specify the type attribute.

<! DOCTYPE html>
 
 

After understanding the process of creating and registering components, I recommend that you use the script> or template> tags to define the HTML templates for your components.
This makes the HTML code and JavaScript code separate, easy to read and maintain.
In addition, in Vue.js, you can create a file with the. Vue suffix and define the components in the. vue file, which I'll introduce in the following article

Component's El and data options

Most of the options passed into the Vue constructor can also be used in vue.extend () or vue.component (), but there are two exceptions: Data and El.
Vue.js stipulates that the data and El options must use functions when defining options for components.

The following code executes, and the browser raises an error

Vue.component (' My-component ', {
 data: {
 a:1
 }
})


In addition, if the data option points to an object, this means that all component instances share a data.
We should use a function as the data option to have this function return a new object:

Vue.component (' My-component ', {
 data:function () {return
 {a:1}}}
)

Using props

The scope of the component instance is isolated . This means that the parent component's data cannot and should not be referenced directly within the subassembly's template. You can use props to pass data to a subassembly.

Props Basics Sample
The following code defines a subassembly my-component and defines the data option in the Vue instance.

var vm = new Vue ({
 el: ' #app ',
 data: {
 name: ' Keepfool ',
 age:28
 },
 components: {
 ' My-component ': {
  Template: ' #myComponent ',
  props: [' myname ', ' Myage ']
 }
 }
}

To make it easier to understand, you can think of this Vue instance as a my-component parent component.
If we want to use the data of the parent component, we must first define the props attribute in the subassembly, that is, props: [' myname ', ' myage '] this line of code.

To define a child component's HTML template:

<template id= "MyComponent" >
 <table>
 <tr>
  <th colspan= "2" >
  subassembly Data
  < /th>
 </tr>
 <tr>
  <td>my name</td>
  <td>{{myname}}</td>
 </tr>
 <tr>
  <td>my age</td>
  <td>{{myage}}</td>
 </tr>
 </table>
</template>

To pass the parent component data through the defined props property to the child component:

<div id= "App" >
 <my-component v-bind:my-name= "name" v-bind:my-age= "Age" ></my-component>
</div>

Note : The CamelCase naming method is used when defining prop in a subassembly. Because HTML features are case-insensitive, CamelCase prop are used for attributes when they need to be converted to kebab-case (dashes are separated). For example, the myname defined in prop needs to be converted to my-name when used as an attribute.

The results of the operation of this procedure are as follows:


How does a parent component pass data to a subassembly? If you look at the following picture, you may be able to understand it well.


When you use a subassembly in a parent component, you pass the data to the child component by using the following syntax:

<child-component v-bind: subassembly prop= "Parent Component data Properties" ></child-component>

Prop type of binding

One-way binding

Since the parent component passes data to a subassembly, does it affect the parent component if the child component modifies the data?
We change the subassembly template and page HTML slightly:

<div id= "App" > <table> <tr> <th colspan= "3" > Parent component Data </td> </tr> <tr> <td>name</td> <td>{{name}}</td> <td><input type= "text" v-model= "name"/></ td> </tr> <tr> <td>age</td> <td>{{age}}</td> <td><input Typ E= "Text" v-model= "age"/></td> </tr> </table> <my-component v-bind:my-name= "name" V-bind:my-a Ge= "Age" ></my-component> </div> <template id= "MyComponent" > <table> <tr> <th Co lspan= "3" > subassembly data </td> </tr> <tr> <td>my name</td> <td>{{myname}}</td&
   Gt <td><input type= "text" v-model= "myname"/></td> </tr> <tr> <td>my age</td&gt
   ; <td>{{myage}}</td> <td><input type= "text" v-model= "Myage"/></td> </tr> </t Able>;/template>

 

Run this page, we do two small trials:

1. Modify the data on the child component on the page


The data for the child component was modified without affecting the parent component's data.

2. Modify the parent component's data on the page


The data of the parent component was modified, and the subassembly was affected.

Prop default is one-way binding: when a parent component's properties change, it is passed to the subassembly, but the reverse does not. This is to prevent the child component from unintentionally modifying the state of the parent component

bidirectional binding

You can explicitly specify bidirectional bindings using. Sync, which allows data modifications of subcomponents to be passed back to the parent component.

<my-component v-bind:my-name.sync= "name" v-bind:my-age.sync= "Age" ></my-component>

single-Time binding

You can use. Once to explicitly specify a single binding that is not synchronized after a single binding is established, meaning that even if the parent component modifies the data, it is not transmitted to the subassembly.

<my-component v-bind:my-name.once= "name" v-bind:my-age.once= "Age" ></my-component>

Example

To digest this knowledge as quickly as possible, let's do a little example.

<! DOCTYPE html>  

In addition to the knowledge points described above, this example also uses two knowledge points:

1. Prop Verification

Props: {
 Data:array,
 columns:array,
 filterkey:string
}

This code indicates that the data and columns that the parent component passes over must be of array type, Filterkey must be a string type.
For more prop verification, please refer to: official documentation prop Validation

2. Filterby Filter
Data can be filtered based on the specified string.

Summarize

The prerequisite for using components is to create and register components, and this article details the steps from creating to using components, it also introduces several different ways to create and register components, and then introduces the props option for components, which is used to pass data from the parent component to the subassembly, and finally we demonstrate the knowledge points with a small example.

This article has been organized into the "Vue.js front-end component Learning course", welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.