JS framework vue.js (in depth three: component 1) _javascript tips

Source: Internet
Author: User
Tags extend inheritance modifier

This is to be written separately, so the original description of the Vue component: Component (Component) is one of the most powerful features of Vue.js. Components can extend HTML elements and encapsulate reusable code. At a higher level, the component is a custom element, and the Vue.js compiler adds special features to it. In some cases, a component can also be in the form of a native HTML element, which is extended in the IS attribute.

This feature I feel more difficult to understand, step by step, to see what the component is exactly what?

1. Give me a chestnut.

Model layer:
//define a Vue component
var mycomponent = Vue.extend by Extend method ({
Template: ' <div>a custom component! </div> '
}
///Register this component with Vue, named My-component
vue.component (' my-component ', mycomponent)
/ Create root instance
new Vue ({
el: ' #example '
})
//vue layer:
<div id= "Example" >
<my-component ></my-component>
</div>

Render as:

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

This is the chestnut, almost fooled me, thinking before the face of the concept of extend misunderstood. Remember the way we described it before.
var mycomponent = Vue.extend (), Vue is equivalent to the base class, MyComponent inherits Vue, has Vue properties and methods, but the concept of inheritance has another layer, which is that the base class is a custom property and method of a subclass. The subclass MyComponent expands a property template, according to inheritance, Vue base class is not available, but this chestnut seems to violate this rule, the last to create a Vue instance, while the template is in effect. Normal writing is not supposed to be like this:

Model layer:
//define a Vue component
var mycomponent = Vue.extend by Extend method ({
Template: ' <div>a cu stom component! </div> '
}]/
/No registration
//vue.component (' my-component ', mycomponent)
//Create MyComponent instance
new MyComponent ({
el: ' #example '
})
//vue layer:
<div id= "Example" >
//No Components
//< My-component></my-component>
</div>

After the experiment, this kind of writing is indeed correct, also can display normally. The problem is, why the first one is also possible, compare the two code, found that the first type of writing has a registration process, registered a my-component, the last use of this my-component, think carefully, not to say Vue instance can use template, Instead of registering this component with Vue, the Vue instance can use this component, so it doesn't conflict. (Scared of the baby--)

When you think about this, consider another question, where is the difference between these two ways?
There is no discovery, the second way of writing is very limited, he replaced the entire Div, no matter how much content in the Div. Like what:

<div id= "Example" >
ssssdfsdaf
<button>abc</button>
</div>

Finally, it was replaced with <div>a cu stom component!</div>. Flexibility is too low, if I only want to replace SSSSDFSDAF what to do? So we have to use the first way, and then awaken to the fact that this is the component, like a part of the same, want to go to which plug:

<div id= "Example" >
<my-template>ssssdfsdaf<my-template>
<button>abc</button >
</div>

In addition, the registration must be before the new instance, and in turn, the newly created instance must not use the component.

The original also said that replace can decide whether to replace, this does not know how to use, first leave a hole in this, the back to see whether to use. Pit 1

2. There are two ways to register a component:

First, see the Global registration method, Vue.component, this global is available.

Second, the local registration method

Local registration can do the same.
var Parent = vue.extend ({
components: {
' my-component ': {
Template: ' <div>a Custom component!</div> '
}}}
)

This is the simplest kind of writing, it is obvious that parent extends Vue and has component my-component. At this point, only parent can use the component, and Vue is not available.

3.is Properties

Components are also restricted in the process of being used. The reason is:

The Vue template is a DOM template that uses the browser native parser instead of implementing one yourself. So the component must be replaced by the normal HTML standard, and it must be a valid HTML fragment. Some HTML elements have restrictions on what elements can be placed inside it. Common limitations:

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

Take table as an example

<table>
<my-component></my-component>
<my-component></my-component>
</table>
//define
var mycomponent = vue.extend ({
Template: ' <tr>a custom component!</tr> ')
})

This seems normal, because the <table><tr></tr></table> structure is normal, but it cannot actually rely on the results of the custom component before the browser is validated, so it is not considered <tr >. To do this, the is attribute works, overwriting the above:

<table>
<tr is= "my-component" ></tr>//Here is changed to IS attribute
<tr is= "My-component" ></tr>
<tr is= "my-component" ></tr>
</table>
//define
var mycomponent = vue.extend ({
Template: ' <div>a custom component!</div> '//here cannot use TR
})

After modification, the equivalent

<table>
<tr><my-component></my-component></tr>
<tr>< My-component></my-component></tr>
<tr><my-component></my-component></ Tr>
</table>

The original TR is preserved, so Dom parsing doesn't go wrong

4.Props: Means of component communication

4.1 "Prop" is a field of component data that is expected to pass from the parent component. Subcomponents need to explicitly declare props with the props option:

Vue.component (' child ', {
//Declaration props, here is the hump-named
props: [' mymessage '],
//templates can be used in this way
Template: ' <span >{{mymessage}}</span> '
})

HTML attributes are not case-sensitive. The name form for CamelCase hump-style prop is used as an attribute, it needs to be converted to Kebab-case (short horizontal), so this looks like this in HTML:

<!--kebab-case in HTML-->
<child my-message= "hello!" ></child>

This is a static use of Props, or it can be v-bind bind dynamic Props to the parent component's data. The child component is also transmitted whenever the data of the parent component changes:

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

At this time see V-model a bit Meng, this goods is not similar to {{}}, referencing the data property of the parentmsg? There must be no parentmsg defined at this point, so v-bind:my-message= the "parentmsg" binding component while giving the parent component parentmsg properties.

Binding type of 4.2 prop:

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-which makes the application's data flow difficult to understand. However, you can also use the. sync or. Once binding modifier modifier explicitly to force bidirectional or single binding:

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

The two-way binding synchronizes the Msg property of the component back to the Parentmsg property of the parent component. The change after a single binding is not synchronized after it is established. Here the original text also highlighted the following, prop is an object or an array, is passed by reference, modify content will modify the content of the parent component at any time, the language based on the know.

4.3 Prop Verification:

Component can specify authentication requirements for props. This is useful when components are used by others, because these validation requirements form the component's API to ensure that others use the component correctly. At this point the value of the props is an object ({} instead of []), containing the validation requirements:

Vue.component (' example ', {
props: {
//underlying type detection (' null ' means any type can be)
Propa:number,
//multiple types (1.0.21+)
propm: [String, number],
//required and is a string
PROPB: {
type:string,
required:true},//
digits, There is a default value of
propc: {
type:number,
default:100
},
//object/array defaults should be returned by a function
propd: {
type: Object,
default:function () {
return {msg: ' Hello '}}}
,
//Specify this prop as bidirectional binding
///If the binding type is not Throw a warning
prope: {
twoway:true
},
//custom validation function
Propf: {
validator:function (value) {
return value >
{}
},
//conversion function (1.0.12 added)
//Convert value before setting value
PROPG: {
coerce:function (val) {
return val + '//convert value to String
}
},
proph: {
coerce:function (val) {
Json.parse (val //Convert JSON string to Object}}
}

Type can be the following native constructor:

String

Number

Boolean

Function

Object

Array

Type can also be a custom constructor, using instanceof detection.

When prop validation fails, Vue will refuse to set this value on the subassembly, and a warning will be thrown if the development version is used.

Here is also a look at my face, not even a chestnut to give, take just the example of a change to make an analogy

Vue.component (' child ', {
//Declaration props, here is the hump-named
props: [' mymessage '],
//templates can be used in this way
Template: ' <span >{{mymessage+1}}</span> '//Convert to Expression
})
<!--kebab-case in HTML-->
<child my-message= " Hello! " ></child>/No change here first

If we want someone to treat the mymessage of the child component as number type, and we do not do prop validation here, the result is that {mymessage+1}} will become a string concatenation, and when HTML is passed into the hello!, Render out Result: hello!

So it's necessary to tell someone to pass in the number type here, so instead:

Vue.component (' child ', {
//Declaration props, where the hump named
props: {mymessage:number},
//templates can be used in this way
template: ' <span>{{mymessage+1}}</span> '//Convert to Expression
})

This time, if the incoming hello! , rendering the results at this time? Yes, it's Nan. So that people would know to pass in a number.
If this is passed in

<child my-message= "123" ></child>//change to 123

This is the head of the bar, run, he meow incredibly still not, or Nan. The original text has this explanation:

#字面量语法 vs. dynamic syntax
//beginners often make a mistake of passing values using literal syntax:
<!--passed a string "1"-->
<comp some-prop= "1" ></ Comp>
because it is a literal prop, its value is passed in the string "1" instead of the actual number. If you want to pass an actual JavaScript number, you need to use dynamic syntax so that its value is evaluated as a JavaScript expression:
<!--pass the actual number-->
<comp:some-prop= "1" ></comp>

Well, that means just passing the string "123", the result must be Nan, and then change:

<child:my-message= "123" ></child>//change to 123

{{mymessage+1}} will get the correct result at this time: 124

The above is a small series to introduce the JS framework of the vue.js (in depth three: component 1), I hope to help you, 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.