Vue Component Mechanism

Keywords: Vue

1 Component Foundation

1.1 Component Concepts

       Components can extend HTML elements by encapsulating reusable HTML, CSS, and JS snippets.
       Components are similar to vue instances, such as having a template attribute inside the component to specify a template and an el attribute inside the vue instance to specify a template.

1.2 Component Features

       (1) Components can be reused any number of times.
       (2) The data of a component must be a function to ensure that each instance maintains a separate copy of the returned object, that is, changes to either component will not affect other components.

1.3 Component Definition

  let component = {
      data() {
        return {
          // Returns a unique copy of the object value, guaranteeing that the internal data of the reused components will not affect each other
          msg: 'I am the component's data'
        }
      },
      template: `
        <div>
          <p>I am a component</p>
          <h1>{{msg}}</h1>
        </div>
      `
    }

1.4 Component Reuse

When component reuse is used, the component modifies the data and the other components do not change the value.

	<div id="app">
        <my-com></my-com>
        <my-com></my-com>
        <my-com></my-com>
        <my-com></my-com>
    </div>
    <script>
        let component1 = {
            data(){
                return{
                    msg:'I am a child'
                }
            },
            template:`
                <div>
                   <h3>{{msg}}</h3>
                   <button @click="msg = 'New Data' ">Modify data</button>
                </div>
            `
        }
   </script>

                                                           

2 Component Registration

       For globally registered components, it can be used within any vue instance or component; Locally registered components can only be used within currently registered instances or components, which is similar to global and local variables in js.

 (1)Global Registration --->Applicable to different components
 	  For parameters within a component: the first parameter is a custom component name; The second parameter is the component configuration item
     	Vue.component('my-com', component);
      If a component is called by more than one other component, global registration is better.
 (2)Local Registration --->Suitable for multiple uses within a scope
      Local registration is better if a component is called multiple times within an instance or component.
	    new Vue({
	       el: '#app',
	       data: {},
	       components: {
	          'my-com': component;//Local registration is registered in the #app instance, where it is used
	       }
	    })

3 Component Interaction/Communication/Value Transfer

3.1 Parent component refers to child component

      The parent component uses the prop property to pass parameters to the child component.

	<div id="app">
	    <my-com :attr1="atrr1"></my-com>
	</div>
	<script>
		let component1 = {
			props:{attr1}
		}
		let vm= new Vue({
            el:"#app",
            data:{
                attr1:'I am the parent component data',
            },
            components:{
                'my-com':component1
            }
        })
	</script>

For props types and validation:

   props Verification:
     let component = {
        props: {
          	title: {
	            type: String,     // Validate data types
	            required: true,   // The parameter that this parameter must pass
	            // Basic data types are written directly after default
	            default: 'Hello',  //  Default value of current parameter
	            // Returns an object or array as a factory function by referencing a data type
	            default() {
	                return { //Return to your default value}  
	            }
	            validator(val) {  // Custom Validator
	                return val.length > 3
	            }
        	}
      	},
     }

3.2 Child component to parent component

      Custom events are a mechanism by which child components pass state to parent components.

	//Subcomponents
	this.$emit('myEvent');  //Subcomponents send data up and carry events
	//Parent Component
	<my-component v-on:myEvent="parentHandler"></my-component>

Specific implementation:

    <div id="app">"
    	//Used to receive data from subcomponents
        <my-com @child-event="parentHandler"></my-com>
    </div>
    <script>
    	let component1 = {
        	data() {
          		return {
            		childData: 'I am subcomponent data';
          		}
        	},
	        template:`
	           <div>
	          	  <h3>Subcomponents</h3>
	              <button @click='toEmitHandler'>Send Events</button>
	           </div>
	        `,
	        methods: {
	           toEmitHandler() {
	           //The $emit method allows you to send events up and carry the data event name: child-event
	           this.$emit('child-event', this.childData)
	        }
         }
      }
      new Vue({
        el:'#app',
        data: {
            parentDate: ''
        },
        methods: {
            parentHandler(data) {
	          	console.log("You said, I know",data);
	            // data is the parameter this.childData is carried with the subcomponent when it sends an event
	            //Modify parent component data, determined by parent component itself
	            this.parentDate = data;
           }
        },
        components: {
            'myCom': component1;
        }
      })
   </script>

3.3 Dynamic Parameter Transfer

      No: - - Constant string passed
      There are: - - passing boolean, number, object, array, variable

3.4 Unidirectional Data Flow

      Updates to the parent's prop data flow down to the child components, which in turn does not work.
      A parent component can modify data in a child component, while a child component cannot directly modify data in a parent component.
Role: Prevents child components from accidentally changing state, affecting state or data in parent components.

Posted by Linjon on Tue, 19 Oct 2021 11:34:34 -0700