Vue.js Customize Components & Communications between Parental Components

What is the component? Component

is one of the most powerful functions of Vue.js, and the core target is to extend the HTML element, encapsulate reusable code. We can put the component code according to the Split mode of Template, Style, Script, and place it in the corresponding .vue file.

The components of Vue.js can be understood as a viewmodel class that predefines the behavior, and one component can pre-define many options, but the most core is the following :


Template

– Template declares the mapping relationship between data and events that eventually present to the user


Initial data (DATA)

– The initial data status of a component. For the reusable components, it is usually a private state

accepted external parameter (PROPS)
– the components pass the parameters Transfer and sharing of data. The default is one-way binding (from top to bottom), but it can also be displayed as bidirectional binding

method (Methods)
The modification operation of the data is generally performed within the method of the component, and the user can be binded to the component method by the V-ON command

Lifecycle Hook Function (Lifecy Hooks)
– A component triggers multiple lifecycle hook functions, such as Created, Attached, Destroyed, etc. In these hook functions, we can package some custom logic. Compared with traditional MVC, this can be understood as the logic of Controller to disperse into these hook functions


Component registration

1, global registration

Vue.Component (Tagname, Options

Vue.Component (‘my-component’, {// option})

As shown above, the first parameter is the name of the registration component (i.e., we can use the components in HTML: ); the second parameter is the constructor of the component, which can be function, It can also be Object

 function - The second parameter can be a component constructor created with Vue.extend ()   
Var mycomponent = Vue.extend ({// option …})


Object – Second Parameter Incoming Option Object Vue.js automatically calls Vue.Extend () // in one step to expand Vue.comPonent (‘Didi-Component’, {Template: ‘

A Custom Component!


After registration, you can customize the element in the module of the parent instance
. To ensure that the components are registered before the initialization root example:   
Global registration case one:


[ 1

 // Register Vue.component ('my-component', {template: ' a Custom Component! 
'}) // Create a root instance new Vue ({EL: '# example')


Global Registration Case 2:


  // Register global component Vue.component ('aaa', {template: '
Name
Li Lei
Male

12 Vue.js  自定义组件 & 父子组件间的通信

Jim


Male

13

Lucy
  Female   '+'   '}; // Create Root Example VAR VM = New Vue ({EL:' # APP ')    
Global registration case three: Female Age: Read Swimming Submit
Name:
// Register global component Vue.component ('# my-component " ); // Creating root instance var VM = new Vue ({EL: '# APP')


Vue.js  自定义组件 & 父子组件间的通信

2, partial registration

 no need for each component Global registration, allowing components to only be used in other components. We can use instance option Components to register    Local registration case one:        
// local registration var VM = NEW VUE ({EL: '# app', component: {'aaa': {template: ''}}})
Local registration case 2:
-> // Register one Submount: '
sub-component data '}; // Registering a parent component var Parent = {// This must be packed with a container to put the registration component, otherwise it will report the error Template: ' Parent component data ', COMPONENTS: {' child ': child}}; // Create an root example new Vue ({EL:' # app ' Components: {//
can only be used in the parent component template 'aaa': parent}}


Vue.js  自定义组件 & 父子组件间的通信





`msg`

`Data`

 VAR VM = New Vue ({EL: '# app', data: {}, components : {'Aaa': {Template: '# bbb', data: function () {return {msg: 'fruits', mydata: [' apple ',' banana ", 'cherry', 'duria']}}} }})        DOM template analysis   
When using the DOM as analog (for example, the EL option is mounted on an existing element), you will be subject to some restrictions on HTML, because VUE is only available. The template content can be obtained after parsing and standardizing HTML. Especially like these elements
, , , limits the elements that can be wrapped by it,

can only appear inside other elements.

When using these restricted elements in custom components, some problems are caused, for example:
[12

Vue.js  自定义组件 & 父子组件间的通信


Custom component

It is considered an invalid content, so it will cause an error when rendering. The scheme is to use special IS attributes:

          It should be noted that these restrictions will not apply if you use a string template from one of the following sources: 
<!-- JavaScript Inline Mode String .VUE Components

Therefore, if necessary, please use String pattern.
For the small example of the IS attribute:
user Name:

Vue.js  自定义组件 & 父子组件间的通信

Sex:

Male

 Female   Gnder: `Gender`       AGE: `Age` 
Interest:

Reading

  • Interest: `Interests`
-> -> -> ->
Office:

Guangzhou Vue.js  自定义组件 & 父子组件间的通信 Beijing

CITY: `CITIES`


      Vue.Component (‘my-row’, {Template: ‘

      Registration Institution:

      ‘ + ‘

      Tsinghua University ‘ + ‘
       Peking University  '+' 
      Harbai Technology University '+' Fudan University
      '+' '+' ‘}) New Vue ({EL:’ # App ‘, Data: {Gnder:’, Age: ‘, Interests: [], CITIES:’ ”}})


       DATA must be a function   When using components, most options can be incomed In the VUE constructor, there is an exception: DATA must be a function. In fact, if you do this: 


      Vue.component (‘My-Component’, {Template: ‘

      `Message`

      ‘, Data: {Message: ‘Hello’}}


      So Vue will issue a warning at the console telling you that DATA in the component must be a function. It is best to understand the existence of this rule.



      VAR DATA = {Counter: 0}; Vue.component (‘Simple-Counter’, {Template: ‘

      `Counter`

      ‘, DATA: function () {Return Data} }) New Vue ({EL: ‘# APP’
        
      to slightly modify the above example, the sample code is as follows: <!-- <!-- It seems that there is no problem, but the page does not render the effect, open the console can see the error message, the DATA function must return an object <!-- PROPS ---> Parent components pass data to sub-component
      Vue.component ('SIMPLE-Counter ', {Template:' ', DATA: Function () {Return {counter: 0}}}) New Vue ({EL:' # App '} Now that each counter has its own internal state:
      The DATA function must return an object
      ` Count` ', data: function () {return count = 0}}) New Vue ({EL:' # APP ')
      Component data transfer assembly means synergistic work,Usually the parent subcomponent is such a relationship: component A uses component B in its temple. They must communicate with each other between them: the parent component is to deliver data to the child component, and the subcomponents need to tell the parent components within what they happen. However, it is important to decouple the parent child component as much as possible in a well-defined interface. This ensures that each component can be written and understood in a relatively isolated environment, which has also greatly improved the maintenanceability and reusability of the components. In Vue.js, the relationship between the parent subcomponents can be summarized as PROPS DOWN, Events Up. The parent component delivers the data to the subcaps by PROPS, and the sub-component sends a message to the parent component via Events. See how they work.
      The scope of the component instance is isolated. This means that the parent components should be directly referenced in the template of the sub-assembly. You can use PROPS to pass the data to the child component.
      The PROP is a custom property for parent components to deliver data. Subcaps need to explicitly declare "PrOP": Vue.component ('Child', {// Declaration PROPS PROPS: ['Message'], // Like data, Prop can be used in template //, like "this.Message" like "this.Message" in the template: ' {mess}} '} Then introduced to it into a normal string:

      First see the first case, do not use the PROPS delivery data Vue.js  自定义组件 & 父子组件间的通信



      Vue.Component (‘Child’, {Template: ‘

      `Message` ‘}) NEW VUE ({EL: “# app”})

      View page, found an error
       "Message" is not defined in the instance, but when rendered, it is quoted in the DATA option, it is necessary to ensure that this property is declared  
      We can modify this:


      Vue.js  自定义组件 & 父子组件间的通信


      Vue.Component (‘Child’, {Template: ‘

      `Message` ‘ , DATA () {Return {Message: ‘Hello, World!’}}}); VAR VM = New Vue ({EL: ‘# APP’)
        
      [12
      The second case uses PROPS delivery data

      Vue.js  自定义组件 & 父子组件间的通信

      Vue.component (‘Child’, {Template: ‘

      `Message`
      ‘, // Declaration PROPS PROPS: [‘Message’]}; New VUE ({EL: “# app”, data: {message: ‘Hello’}})

      At this time, the page You can render you from
        
      At the same time, pay attention to observing the above code, and there is a favorite Message in the Vue instance. Attribute 'Hello', but the page rendering is Hello. This returns to the role of PROPS.
      The scope of the component instance is isolated, That is, even if there is the same name between the components and components, the value is not shared


      Vue.js  自定义组件 & 父子组件间的通信


      New Vue ({EL: ‘# App’, Components: {‘Component1’: {TEMPlate: ‘ `msg` ‘, data: function () {return {msg: ‘component one’}}}, ‘Component2’: {Template: ‘

      ` msg`

      ‘ , DATA: FUNCTION () {RETURN {MSG: ‘Component 2’}}}}}

        
      Two components are used The same attribute MSG, but the content of rendering is different Let's see example, imitate the post comment ""点 赞 "and" opposition "function:


      `Heading`

      ` count`

      Vue.js  自定义组件 & 父子组件间的通信


      VAR VM = New Vue ({EL: ‘# App’, Components: {‘counter’: {Template: ‘# counter-template’, data: function () {return {count: 0}}}}}}


      As shown in the following figure, the page prompt error reports, Heading is not defined, requiring declarations in the DATA property. Also mentioned previous example, you may return to a heading of the data object function, but here the value heading is dynamic, may Like Dislike may be, so the best way is to follow the rules, the parent component counter To pass the data of the child component template to PROPS


      Add a PROPS attribute:

      Vue.js  自定义组件 & 父子组件间的通信 VAR = New Vue {EL: ‘# App’, Components: {‘counter’: {template: ‘# counter-template’, // Press the parent component counter to the data of the child component template PROPS: [‘Heading’] , DATA: Function () {Return {Count: 0}}}}})

      Normal display:


      Here, add a color prompt, the point of praise is green, the opposition button is red


           


      `Heading `

      VAR VM = New Vue ({EL: ‘# App’, Components: {‘Counter’: { Template: ‘# counter-template’, // Press the parent component counter to the data of the child component Template PROPS: [‘Heading’, ‘Color’], Data: Function () {Return {Count: 0 }}}}}
           
      There are two identical properties Heading and Color, but the scope is different. So the color and content of the rendered are different.


      In this example, Counter as a parent component, Counter-TemplaTE as a sub-assembly, parent component transmits data “Likes, Dislikes, Green, Red” to the subcomponent, subgroup to send messages to parent components by clicking on event

        
      Hump nomenclature VS short horizontal nomenclature HTML characteristics are not case sensitive. When a non-template string, prop will be converted from the form name camelCase kebab-case (separated by hyphens):


      Vue.component ( ‘child’, {// camelCase in JavaScript props: [ ‘myMessage’], template: ‘

      {{myMessage}}

      Vue.js  自定义组件 & 父子组件间的通信

      Refactor again if you use a string template, do not care about these restrictions. Look at the page effect of two different naming methods

      Dynamic PrOPS
         Similar to the HTML feature of the V-BIND to an expression, you can also use the V-BIND to dynamically bind the value of the PROPS to the data of the parent component. Whenever the data changes to the parent component, the change will also be transmitted to sub-components:      Syntax:   
      Vue.component (‘Child’, {Template: ‘

      `MyMessage`
      ‘, PROPS: [‘mymessage’]}) New Vue ({EL: ‘# app’, data: {parentmsg: ‘ ‘}})

      Vue.js  自定义组件 & 父子组件间的通信


      Again to see an example:

        
      VAR VM = New Vue ({DATA: {H: 'Hello'}: {'Child': { PrOPS: ['btn'], Template: '
      `BTN` ', DATA: FUNCTION () {return {'btn': 123} // The property of the sub-component is overwritten by the parent component}}} }}). $ Mount ('# app'); According to the previous statement, whenever the data of the parent component changes The sub-assembly will also change. That is, the BTN attribute in this example in the Child subcaps is always covered by the H attribute in the parent component



      Changing the value of the H attribute in the parent component, the content in the sub-component will change Vue.js  自定义组件 & 父子组件间的通信


      Word Surface Syntax VS Dynamics


      An error in the initiator is using a literal quantity Syntax transmission value:



      because it is one Field PROP, its value is “1” instead of the actual number to pass. If you want to pass an actual JavaScript number, you need to use V-bind, so that its value is calculated as JavaScript expression:

        
      The above content is provided by the official document, and the brief understanding is: (1), does not add V-bind The passed is a string, even if it is a number 1, it is also a string, not Number

      (2), plus V-bind is passed to the JavaScript expression, so that the value in the parent component can be transferred

      (3) After adding V-bind, if the value of the parent component can be found, use the value of the parent component; if I can't find i, it will be regarded as a JavaScript expression (for example, 1 + 2 3, {a: 1} See as an object)
      Language syntax sample code (no V-bind):


      Vue.js  自定义组件 & 父子组件间的通信

      VAR VM = New Vue ({El: ‘# app’: {Props: [‘MSG’], Template: ‘

      `MSG`
      ‘}}})


              Dynamic speech example code (plus V- Bind):    
      VAR VM = New Vue ({EL: '# App ', Components: {' Child ': {Props: [' MSG '], Template:'
      `MSG` '}}})

      One-way data stream


      The PROP is one-way binding: When the attribute of the parent component changes, it will be transmitted to the sub-assembly, but will not be reversed. This is to prevent the child components from unintentional to the state of the parent component – this will make the application’s data streams difficult to understand.

      Vue.js  自定义组件 & 父子组件间的通信

      Binds the modifier (Vue2.0 has been removed. Sync and .once), only do understanding, focus on the one-way binding

      .sync —> Bidirectional binding
        .once -> Single binding  


      Vue.js  自定义组件 & 父子组件间的通信



       Example 1: One-way binding:       subassembly:   
      VAR VM = New Vue ({EL: '# app', data: {msg: 'Hello World'}, Components: {'Child': {Props: ['Message'], Template: ''}}}

      Modify the content of the parent component, the sub-component changes:
      Modify the contents of the subcomponents, the console is reported immediately: Probably
      Avoid directly changing a Prop because the value of the parent component is overwritten, and one can be used PROP-based DATA or COMPUTED attributeAlternative



      Example 2: Bidirectional binding: (Vue2.0 does not support, and will report the same Error)

      Parent component:

      Vue.js  自定义组件 & 父子组件间的通信 subassembly:


      VAR VM = New Vue ({EL: ‘# app’, data: {msg: ‘Hello World’}, Components: {‘child’: {PROPS: [‘Message’], Template: ‘

        The content of the sub-assembly is changed, and the parent component is also followed. Remind again: Vue2.0 does not support this usage     
      can be seen in the example one in the above When each parent component is updated, all PROPs of the sub-component will be updated to the latest value. This means you should change the Prop inside the subcombium. If you do this, Vue will give a warning at the console.
          There is usually two cases of changing Prop:  


      1, PROP is incorporated into the initial value, subassembly After that, it is only used as the initial value of the local data;

      Vue.js  自定义组件 & 父子组件间的通信 2, PROPThe original value of the transition is required.


      More specifically, these two situations are:

      1, define a partial DATA attribute and will The initial value of the PROP is the initial value of local data.

      PrOPS: [‘INITIALCUNTER’], DATA: Function () {Return {counter: this.initialcounter}}


      2, define a compute property, this property is calculated from the value of the PROP. PROPS: [‘size’], computed: {normalizedsize: function () {return this.size.trim (). ToolowerCase ()}}


      Note Objects and arrays in JavaScript are reference types, pointing to the same memory space, if PROP is an object or array, change it within the subcomponents to affect The status of the parent component.

        

      PROP verification

      Components can specify verification requirements for PROPs. If the verification requirements are not specified, the Vue will warn. This is useful when the components are used by others.
      PROP is an object rather than a string array, which contains verification requirements:

      Vue.js  自定义组件 & 父子组件间的通信

      Vue.comPonent (‘example ” {PROPS: {// Basic Type Detection (`Null` means any type can be) Propa: Number, // Multi-type Propb: [String, Number], // Biography and string PROPC: {TYPE: STRING , Required: true}, // Number, with default value Propd: {type: number, default: 100}, // array / object’s default value should be represented by a factory function: {type: object, default: function ) {Return {message: ‘Hello’}}}, // Custom Verification Function Propf: {Validator: Function (Value) {Return Value> 10}}}})


       TYPE can be the following native constructor:  
      Number Boolean Function
      OBject
      Array


      TYPE can also be a custom constructor that is detected using InstanceOf.

      When the PROP verification fails, the Vue will reject this value on the subcomponent, if used, the development version will throw a warning.

      Summary: Subcaps To obtain parent components DATA

      Vue.js  自定义组件 & 父子组件间的通信

      Vue.js  自定义组件 & 父子组件间的通信 in the call sub-assembly :


      Inside the sub-assembly:
      PROPS: [‘m’, ‘mymsg’]

      PROPS: {
       'M': String,   'mymsg': Number  }  


      The subassembly sends data to the parent component
        parent components It is to transfer the data to subcaps using PROPS, but what if the sub-component is passed back, what should I do? That is the custom event     
      Use V-ON binding custom event


      Each Vue The instance implements the event interface, namely:

      > listening to the event

      $ EMIT (Eventname)
      Trigger Event

      Vue event system separates the EventTarget API of the browser. Although their operation is similar, $ ON and $ EMIT are not an alias of AddeventListener and DispatChevent.
        
      In addition, the parent may use v-on to monitor where the use of sub-assemblies directly incident subcomponents triggered

      parent component:

      `Total`

      subcomponent:

      Vue.js  自定义组件 & 父子组件间的通信

      VAR VM = New Vue ({EL: ‘# App’, Data: {Total: 0}, methods: {Incrementtotal: function () {this.total + = 1;}}, component: {‘button-counter’: {PROPS: [], // The parent component does not send data from the subcomponent, so it does not need template: ‘
      `Counter`

      ‘, // Data must be a function and return an object data: function () {return {counter: 0}}, meThods: {increment: function () {this.counter + = 1; this. $ EMIT (‘increment’)}}}}})

        
      In this example, the sub-assembly has been fully decoupled with it outside. It only triggers an internal event of a parent component concerned
      Sample code 2:


      Vue.js  自定义组件 & 父子组件间的通信


      The data of the parent component is:

      —> `Parentmsg`
      The data of the subassembly is:

      -> `Childmsg`

      Send

      VAR Parent = Vue.component (‘Parent’, {Template: ‘# PARENT- Template ‘, Data () {Return {Parentmsg: ‘111 ‘}}}); var Child = Vue.component (‘ child ‘, {template:’ # child-template ‘, data () {return {childMsg:’ 99999 ‘}}}) var vm = new Vue ({ EL: ‘# App’, Components: {‘Parent’: Parent}


      Two components are prepared, the desired goal is to click the send button, send the data of the sub-component to the parent component, replace 111

      with 99999 Note: Core 2

      VM. $ EMIT (Custom Event Name, Data)

      V-ON: Custom Event Name = Method
                  



      The data of the parent component is:

      —> `Parentmsg`
        
      The data of the component is:
      ---> `Childmsg` Send
      // Registered Parent Components Var Parent = Vue.component ('Parent', {Template: '# Parent-Template', DATA () {Return {ParentMSG : '111'}}, // Receive sub-components pass data Methods: {Get: function (msg) {Alert (msg); this.parent msg = msg;}}}); // Register sub-component var child = Vue.component ('Child', {Template: '# {return {childmsg:' 99999 '}}, // Send sub-component data to the parent component methods: {send: function () {This. $ EMIT ('get-message', this.childmsg)}}}; var VM = new Vue ({EL: '# app', components: {'parent': parent});


      Vue.js  自定义组件 & 父子组件间的通信


      When using components, it is often like this to combine them:


      Vue.js  自定义组件 & 父子组件间的通信


      Watch two points:
        

      1, Components don't know what it will have a mount point. The content of the mount point is determined by the parent components of .
      2, Components are likely to have its own template.
      In order to make the component can be combined, we need a way to mix the contents of the parent component and the child components themselves. This process is called
      content distribution (or “transclusion” if you are familiar with Angular). Vue.js implements a content distribution API, referring to the current WEB component specification, use special


      elements

      as the original content

      slot

      .

      Vue.js  自定义组件 & 父子组件间的通信

      In order to avoid being drawn by words, directly on the previous code is understood:



      Apple

      Banana

      orange



      var vm = new Vue ({el: ‘# app’, components: { ‘parent’: { template: ‘?

      fruits, fruit, where

      ‘}}})


         
      here the definition of a parent component, then gave the parent defines a template h2, the effect of the final show but did not list ul


      the solution is to use content distribution, i.e. the aforementioned

      slots, slot intention is “position, the groove” is here simply occupy positions
         
      1, a single slot

      SUMMARY

      parent element will be discarded, unless the sub-assembly comprising a template

      . If the child is only one component template is not characteristic of the slot, the entire contents of the parent component into the place where the slot and replace it.

      SUMMARY
      label of the content fallback fallback content in compiling scope subassembly, the display element is empty when the host and which are not inserted fallback content.


      with minor modifications to the above code



        Orange  


      Fruit, Where is the fruit, where?

      VAR VM = New Vue ({EL: ‘# App’, Components: {‘Parent’: {Template: ‘# FRUIT ‘}}}


      page effect:

      element can be configured with a special feature Name to distribute content, multiple SLOT can have different The name, the name of the name of the Slot will match the elements of the corresponding slot feature in the content clip


      can still have an anonymous Slot, as a fallback of the matched content segment Slot, it is the default slot. If there is no default slot, these can’t find the matching content clip will be abandoned



      Apple

      Banana

      Orange


      White Radish


      Fruit, Where is the fruit, where?

      This is the default case

      This is the default case 2



      VAR VM = New Vue ({EL: ‘# App’, Components: {‘Parent’: {Template: ‘# FRUIT’}}})





      dynamic components


      A plurality of components can use the same mount point and then dynamically switch between them. Using the retained

      element, it is dynamically bound to its IS characteristic


      example code





      VAR VM = New Vue ({EL: ‘# App’, Data: {A: ‘AAA’}, Components: {‘AAA’ : {Template: ‘

      I am AAA component >’}, ‘bbb’: {template: ‘ I am BBB component

      ‘}}}
        


      Sample Code 2:


      Fast

      Vue.js  自定义组件 & 父子组件间的通信


      Business

           VAR VM = New Vue ({EL: '# App', Data: {CurrentView: 'Fast', Show: false}, Components: {'fast': {Template: ' Drop Express '}, 'Bus': {Template:'  Tick Bus  '},' Business ': {Template:'  
      '}}
      The VM.CurrentView variable value bound by IS attribute is controlled, and the effect is as follows:
      [12
      If the component switched out is retained in memory In, you can retain it or avoid re-rendering. To do this, a Keep-Alive instruction parameter can be added.
      Vue.js is designed for its components The characteristics of [Keep-alive], if this feature exists, then quickly create components through the cache mechanism when the component is repeatedly created, to enhance the performance of the view update.

      Vue.js  自定义组件 & 父子组件间的通信

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment