Introduction to Components
The component system is one of the important concepts of vue.js, which provides an abstraction that allows us to build large applications using independent 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 treat components as custom HTML elements.
The demo and source code of this article has been put on GitHub, if you think this is a good content, please click to praise, or add a star on GitHub!
Component one-way binding component two-way binding component one-time binding Page Demo GitHub Source
Due to the large size of the components, I will be the component of the introduction of knowledge into two pieces to explain, so that you can crossing quickly digest.
Basic steps for creating and registering components
The use of Vue.js components is 3 steps: Creating a component constructor, registering components, and using components.
The following code demonstrates these 3 steps:
<! DOCTYPE html>
The results of the operation are as follows:
As you can see, there's no difference between using components and using plain HTML elements.
Understanding the creation and registration of componentsWe use the following steps to understand the creation and registration of components:
1.Vue.extend()
is an extension of the Vue constructor, calledVue.extend()
Creates a component constructor instead of a specific component instance.
2.Vue.extend()
The constructor has an option object, an option objecttemplate
property is used to define the HTML that the component will render.
3. UseVue.component()
When registering a component, you need to provide 2 parameters, a 1th parameter when the component is labeled, and the 2nd parameter is the component constructor.
4.Vue.component()
The component constructor is called inside the method to create a component instance.
5. The component should be attached to a Vue instance, or it will not take effect.Please note that 5th, the following code uses <my-component> tags in 3 places, but only the <my-component> tags under #app1 and #app2 play a role.
<! DOCTYPE html>
View Demo
Global registration and local registrationVue.component()
when you invoke the registration component, the registration of the component is global, which means that the component can be used under any Vue sample.
If global registration is not required, or if the component is used within other components, Local registration can be implemented with the components of the option object .
The above example can be changed to a partial registration method:
<! DOCTYPE html>
Because the My-component component is registered under the Vue instance corresponding to the #app element, it cannot be used under other Vue instances.
<div id= "APP2" ><!--cannot use the My-component component because my-component is a local component and it belongs to #app--><my-component></ My-component></div><script>new Vue ({el: ' #app2 '});</script>
If you do this, the browser will prompt an error:
View Demo
Parent and child componentsWe can define and use other components in the component, which forms the relationship of the parent-child component.
<! DOCTYPE html>
The result of this code operation is as follows:
Let's take a few steps to understand this piece of code:
var Child = Vue.extend(...)
Define a child component constructor
var Parent = Vue.extend(...)
Define a parent Component Builder
components: { ‘child-component‘: Child }
, register the child component with the parent component and set the child component's label 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)
Globally registering the parent component
- Renders the contents of the parent component in a page using the <parent-component> tag, 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: a subcomponent can only be used in the template of the parents component.
Please note that the following two seed components are used in a wrong way:
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 subcomponent is registered with the parent component, Vue.js compiles the parent component's template, and the content of the template determines the HTML that the parent component will render.
<parent-component>…</parent-component>
Equivalent to the runtime, some of its sub-tags will only be used as normal HTML to execute,<child-component></child-component> is not a standard HTML tag, will be ignored by the browser directly.
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 will prompt the following error
View Demo
Component registration Syntax sugarThe above component registration method is somewhat cumbersome, vue.js in order to simplify this process, provides the registration syntax sugar.
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 first component!</div > '}) var vm1 = new Vue ({el: ' #app1 '})
Vue.component()
The 1th parameter is the label name, the 2nd parameter is an option object, and the component template is defined using the template property of the option object.
In this way, Vue is automatically invoked behind the scenes Vue.extend()
.
Partial registration is implemented in the components property of the option object:
var vm2 = new Vue ({el: ' #app2 ', components: {//partial registration, My-component2 is the 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 script or template tagsAlthough syntactic sugar simplifies component registration, it is cumbersome to stitch HTML elements in the template option, which also leads to high coupling between HTML and JavaScript.
Fortunately, Vue.js provides two ways to separate HTML templates that are defined in JavaScript.
Use <script> tags
<! DOCTYPE html>
The template option is now no longer an HTML element, but rather a id,vue.js that finds the corresponding element based on that ID, and then compiles the HTML within the element as a template.
Note: when using the <script> tag, the 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> tag when parsing an HTML document.
Use <template> tags
If you use <template>
a label, you do not need to specify the Type property.
<! DOCTYPE html>
After understanding the component creation and registration process, I recommend using the <script> or <template> tags to define the HTML template for the component.
This makes the HTML code and the JavaScript code separate and easy to read and maintain.
In addition, in Vue.js, you can create a. vue suffix file that defines the component in the. vue file, which I'll cover in a later article.
El and data options for componentsMost options for passing in the Vue constructor can also be used in Vue.extend()
or Vue.component()
, but there are two exceptions: data
and el
.
Vue.js: When defining options for a component, the data and El options must use functions.
When the following code executes, the browser raises an error
Vue.component (' my-component ', {data: {a:1}})
Also, if the data option points to an object, this means that all component instances share a single data.
We should use a function as the data option and let the function return a new object:
Vue.component (' My-component ', {data:function () {return {a:1}}})
Using propsThe 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.
Props Basic ExampleThe following code defines a subcomponent, my-component, that defines the data option in the Vue instance.
var vm = new Vue ({el: ' #app ', data: {name: ' Keepfool ', age:28},components: {' my-component ': {Template: ' #myComponent ', prop s: [' myName ', ' MyAge '}}})
For ease of understanding, you can think of this Vue instance as the parent component of my-component.
If we want to make the parent component's data, you must first define the props property in the subassembly, props: [‘myName‘, ‘myAge‘]
which is the line of code.
To define the HTML template for a subcomponent:
<template id= "MyComponent" ><table><tr><th colspan= "2" > sub-assembly Data </th></tr><tr ><td>my name</td><td>{{myName}}</td></tr><tr><td>my age</td> <td>{{MyAge}}</td></tr></table></template>
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: when defining prop in subcomponents, the CamelCase nomenclature is used. Because HTML attributes are not case-sensitive, the CamelCase prop is used for attributes that need to be kebab-case (dashes separated). For example, a myname defined in prop needs to be converted to my-name when used as an attribute.
The results of this program run as follows:
How does a parent component pass data to a child component? Believe you see the following picture, maybe you can understand well.
When you use subcomponents in a parent component, you pass the data to the child components by using the following syntax:
<child-component v-bind: subcomponents prop= " Parent Component Data Properties " ></child-component>
Prop binding Type one-way bindingNow that the parent component passes the data to the child component, does it affect the parent component if the child component modifies the data?
We make a minor change to the subcomponent template and the page HTML:
<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 type= "text" v-model= "age"/></td></tr></ Table><my-component v-bind:my-name= "name" v-bind:my-age= "Age" ></my-component></div>< Template id= "MyComponent" ><table><tr><th colspan= "3" > Sub-component Data </td></tr><tr> <td>my name</td><td>{{myName}}</td><td><input type= "text" v-model= "MyName"/> </td></tr><tr><td>my age</td><td>{{MyAge}}</td><td><input Type= "text" v-model= "MyAge"/></TD></TR></TABLE></TEMPLATE>
View Demo
To run this page, we do two small experiments:
1. Modifying sub-component data on the page
The child component's data is modified without affecting the parent component's data.
2. Modify the parent component's data on the page
The parent component's data is modified, and the subcomponents are affected.
Prop default is one-way binding: When the parent component's properties change, it is transmitted to the child component, but not vice versa. This is to prevent the child component from unintentionally modifying the state of the parent component in two-way bindingYou can explicitly specify a two-way binding by using. Sync, which causes the child component's data modifications to be passed back to the parent component.
<my-component v-bind:my-name.sync= "name" v-bind:my-age.sync= "Age" ></my-component>
One-time bindingYou can use. Once to explicitly specify a single binding, and a single binding does not change after it is established, which means that even if the parent component modifies the data, it is not transmitted to the child component.
<my-component v-bind:my-name.once= "name" v-bind:my-age.once= "Age" ></my-component>
View Demo
ExampleIn order to digest this knowledge as soon as possible, let's make a small example.
<! DOCTYPE html>View Demo
In addition to the above mentioned knowledge points, this example also uses two knowledge points:
1. Props Verification
Props: {data:array,columns:array,filterkey:string}
This code means that the data and columns passed by the parent component must be of type array, and the filterkey must be of type string.
2. Filterby Filter
Data can be filtered according to the specified string.
SummarizeThe prerequisite for using the component is to create the component and register the component, this article details the steps from creation to use of the component, describes several different ways to create and register the component, and then describes the component's props option, which is used to pass the parent component's data to the child component. Finally, we illustrate these points with a small example.
vue.js--60 minute Widget Quick Start (previous)