Usage: When a type of component needs to be used multiple times, each call is only different in a specific place, just like A personal profile form, the information filled in by the person is different every time, but the structure is the same.
Introduce the sub-component into the parent component, pass the parameters through the label attribute of the sub-component, and define a props option in the sub-component to receive it When using it, please note that there is no need to define it in advance in the subcomponent outside of props.
##You can see above that the age passed in is a string type. If you want the passed in value to automatically increase by 1, you cannot add 1 when using the subcomponent. As shown in the figure below, it will become String addition 241 The correct solution is to use v-bind for dynamic binding when the parent component passes parameters. Defined, or you can use a colon: (short form), the function is to run the expression inside the quotation marks and return the running result, as shown in the figure below Usage 2 (accept simultaneous type restrictions): If the parameter type passed in is inconsistent with the specified type, the type passed in will take precedence and a warning will be issued. Usage 3 (accept simultaneous type restriction default value specification): There are two options after specifying the type , one is to specify whether it is necessary, and the other is the default value when not passed##Note:
In addition, after testing, this method can only be used in data and cannot be used in setup
emit use
As shown in the figure below, props is the information passed by the parent component to the child component as mentioned above, as shown in the figure below
Now the focus is on emit, emit is a thing in context
Function: used to trigger binding in the parent component function and can pass parameters back to the parent component As shown in the configuration in the parent component APP.vue, a function xxx is bound to the sub-component
Now come to the sub-component. A button is bound to an event in the sub-component to trigger the event of the parent component. xxx1 and passed a string " " back,
Finally got the following effect, every time the button in the sub-component StDent is clicked , a string attribute in the parent component will automatically add two and display them
emit summary: After the above example, we only need to know that emit is a function that allows child components to trigger parent components.
The above is the detailed content of How to use props and emit in Vue3. For more information, please follow other related articles on the PHP Chinese website!