Analysis of the application of Vue components - communication between parent and child components

1. Three steps for component usage:

  1. Create a component constructor: call the Vue.extend() method to create a component constructor;
  2. Register component: Call the Vue.component() method to register the component;
  3. Using Components: Use components within the scope of a Vue instance.

Examples are as follows:

(1) A simple case of local components and global components

(2) A simple case of parent and child components:

2. Syntactic sugar for registering components:

(1) The method of defining global components:

(2) The method of defining local components:

Syntactic sugar is written as follows (omit the extend method, and write the corresponding component directly into the component method):

3. Save component data (function data() must be used).

Due to the reusability of components, the purpose of using the function method is to prevent multiple component objects of the same type from sharing a data and causing pollution. However, due to the limitation of scope, the function can prevent the interference of data generated by each component.

4. Communication method between parent and child components:

(1) The parent component passes data to the child component through props (passable array or object);

Step1: Define a variable array/object in props to point to the data in the parent component

Note: For example, for wballstars named in props, if you want to dynamically bind the data in the parent component with camel case, you must write it as w-ball-stars and use the syntax of - connection (as shown in the figure, if it is defined as wBallStars, dynamically bind Regularly use - for case sensitivity) .

Step2: Dynamically bind the data in the parent component where the component is used in the html file

Supplement: props (passable array or object), now develop multi-purpose objects

Pass the array:

pass object:

(2) The child component sends information to the parent component through the event

Step1: The child component is created by the methods method and emits an event (including the event name and passed information) to the parent component

Step2: The parent component calls the methods method of the parent component by listening to the event to complete the corresponding function

5. Access between components: use children or ref for access.

case:

(1) Use children (the children array in this case has 3 data):

The code in the methods of the parent component:

(2) Use ref

The code in the methods of the parent component:

6. Subcomponent access to parent component: parent or root

But pay attention to the difference between the two (parent is to access the upper-level component or vue instance, root is to access the root component, that is, the vue instance)

Guess you like

Origin blog.csdn.net/NXBBC/article/details/123410873