This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!

This article for the nuggets technology community first, unauthorized prohibit to reprint!

preface

In order to have a better grasp of Vue, I intend to relearn Vue3 from understanding basic usage to simulating implementation!

This article is the second in a series: Dive into components

Due to its long length, I have divided this part into two parts in order to improve the reading experience. This part is the first part

You will reap

By the end of this article, you should have a clear idea of the component-related details that will help you solve most of the component-related problems you encounter in your daily development

In this paper, characteristics of

  • Case with animation

The benefit is that it’s not boring, it helps you quickly understand the components, and it’s easy to review and refer to later

note

This article requires you to have the foundation of part 1, which can be moved on:

  1. 10 maps show you quick start Vue3 | Gao Qingyuan attached figure
  2. Understand the application examples and component instance | relearn Vue3
  3. Understand the template syntax | relearn Vue3
  4. Deep understanding of the data and the methods of configuration options | relearn Vue3
  5. Understanding calculate attribute and listener | relearn Vue3
  6. The binding class and inline style style | relearn Vue3
  7. Understand the conditions for rendering | relearn Vue3
  8. Understand the list rendering | relearn vue3
  9. Understand the event handling and related modifiers | relearn Vue3
  10. V – model and its modifiers | relearn Vue3
  11. Component of the basic use | relearn Vue3

Focus on the first article, and take a good look at the basic use of the components in the last article if you have time

The directory structure

The directory structure for this article is as follows

Certified components

This is divided into the following three parts

Component name

When registering a component, you need to provide a name as the component name

When using components in the DOM, it is recommended that component names be all lowercase and contain a hyphen of ‘-‘ to avoid conflicts with future HTML element names

Example: 🌰 : Define a component named my-Component

When defining a component in a string template or a single file component, the component name can be kebab-case or PascalCase

  • If you use kabab-case, you also need to use kabab-case where you use it

  • If you use PascalCase, you can use either PascalCase or kabab-case at the point of use, except that only kebab-case is valid in the DOM if the point of use is in the DOM

Example 🌰 : use PascalCase when defining and use kebab-case and PascalCase in the DOM

Finding that only kebab-case can be displayed, the second Vue raises a warning

Therefore, it is recommended to use kabab-case when defining component names

Global registration

As in the previous example, components registered through the Component method on the application instance are global components

Global components can be used in the template of any newly created component instance

Example 🌰 : Define two global components, using one component in the other component template

As you can see, the component that was placed in another component is also rendered

Global registrations are flawed and may cause users to download unnecessary JS code, so local registrations can be used instead

Local registration

Register local components using the component’s configuration option Components

  • First declare a plain JS object to define the component
  • Then register in the Components option

For each property in components, the property name is the custom element name and the property value is the component’s option object

Example 🌰 : Register two local components component-1 and component-2 with components

Note: A locally registered component is not available in its children, that is, component-2 cannot be used in Component-1. If it is used, it must be registered in component-1’s configuration item Components, just as a local component is registered

It can be registered locally in the module system

Example 🌰 : Import component configuration through modularization and import the configuration to components

summary

For convenience, I’ve put the content of the registered components together in one diagram

Component Props

Here is divided into the following five parts

Type of property

In the component configuration item props, properties of a component that can be listed as an array of strings

For example 🌰 : Add a custom attribute author and list it in props

You can also specify a value type for each attribute as an object in props

Example 🌰 : Set the type of author to a string

The benefits of specifying an attribute type

  • You provide documentation for the component
  • The browser console prompts you when you enter an incorrect type

Static and dynamic properties

Passing static properties

In the example above, when using a component, you add the property author directly to the component, and you can pass a static property value, LBJ, to the property

Passing dynamic properties

When working with components, you can use V-bind to dynamically assign values to properties

Can be assigned to a number, Boolean, array, object, etc

Example 🌰 : Add a dynamic attribute like with a numeric value to the component

You can use V-bind with no arguments to pass in all of an object’s properties as a prop for the component

Example 🌰 : Use v-bind with no arguments on a custom my-component

You can see the final result, where the object passed in is expanded

Single data flow

Updated prop from the parent component flows down to the child component, and Vue warns if it does not

Example 🌰 : Modify the title data in the sub-component

Vue WARN]: Attempting to mutate prop “title”. Props are readonly

This is good because it prevents the child component from accidentally changing the state of the parent component, making the application’s data flow difficult to understand

When the prop value of the parent component changes, all prop values in the child component are refreshed to the latest value

If you really want to change a prop inside a child component, there are two possible scenarios and what to do

Case 1: The prop passes an initial value as local data for the child component

Recommended practice: Declare a property in the data of the child component with the value of prop

Example: 🌰 : The parent component passes initialCounter, and the child component declares another variable that assigns the value of initialCounter

In the future, if you want to modify it, just modify counter directly

Case 2: This prop passes an initial value that needs to be evaluated or transformed in a child component

Recommended practice: Define a corresponding computed property in a child component

Example 🌰 : The parent component passes size, and the child component recalculates a value normalizedSize by evaluating the property

In particular, for a prop of an array or object type, changing the object or array itself in a child component will affect the parent component

Property verification

Property validation is helpful for people who use components

Attribute authentication mode

To specify the validation method, simply give the component’s props a specific object whose property name, even the component prop, is the corresponding validation

Example 🌰 : The authentication modes are as follows

PropA: Number Indicates that the value type of propA is Number

PropB: [String, Number] indicates that propB’s value type is String or Number

PropC: {type: String,required: true} Indicates that the type is String and mandatory

In addition to the above, there are other verification methods:

PropD: {type: Number,default: 1} indicates that the type is Number and has a default value

PropE: {type: Object,default() {return {message: ‘hello’}}} indicates that the default value is an Object. Note: The Object or array default value must be obtained from a function

PropF: {validator(value) {return [‘success’,’warning’, ‘danger’].includes(value)}} Indicates a custom validation function

PropG :{type:Function,default(){return ‘XXX’}} Indicates that the type is Function with default values. In development environments, Vue will warn when prop validation fails

Note: Property validation is performed before the component instance is created, so properties for all component instances such as data, computed, and so on are not available in default or Validator functions

Type the type of

It can be one of the following native constructors: String, Number, Boolean, Array, Object, Date, Function, Symbol

It can also be a custom constructor

Example 🌰 : Use a custom constructor as a type

Case name of Prop

Attribute names in HTML are case insensitive, so the browser interprets all uppercase characters as lowercase characters

Therefore, when registering components, prop names use camelCase (camel nomenclature), and prop names need to be written in HTML equivalents

Example 🌰 : Used when registering components, the prop name is camelCase

If used in a string template, there is no restriction and either camelCase or kebab-case can be used

summary

For convenience, I summarized the related content of the registration Props into a figure

Nonattribute property

Here is divided into the following four parts

concept

Non-prop attributes refer to features in the component that are not defined in the props or emits options

Common examples are class, style, id, and so on

Non-attribute attributes have the property of inheritance

Inheritance means that when a component returns a single root node, non-prop attributes are automatically added to the attributes of the root node

Inheritance also applies to event listeners, which are passed from parent to child components

Example 🌰 : Add a class property and an event onclick to the component

As you can see, ultimately both properties inherit from the root node of the component

Event listeners need to pay attention to whether the event matches the root node

Disables inheritance of non-attribute features

Set inheritAttrs: False in the component’s options

Example 🌰 : Add inheritAttrs:false to the preceding example

You can see that non-props features are not inherited from the Button node

$attrs

You can access these non-attribute features using the component’s $attrs attribute

Example: 🌰 : find all non-attribute attributes through $attrs

You can then batch add all non-attribute features to the specified node with v-bind=”$attrs”

The same goes for multiple root nodes, allowing inheritance of non-attribute properties for a particular node

summary

For convenience, I’ve summarized the non-attribute features in one diagram

Custom events

Here is divided into the following five parts

Define custom events

Custom events can be defined in the component emits option, and all event names can be packed in an array

For example 🌰 : In the emits selection, place a custom event inFocus

When native events (such as click) are defined in the emits option, they are replaced by events in the component

Dispatch events and listen events

You can send events and pass parameters through $emit() in a child component

this.$emit('submit', { email, password })
Copy the code

You can listen for events via V-ON in the parent component

Example 🌰 : Trigger my-event event in child component and listen for event in parent component

The event name

Event names for custom events provide automatic capitalization conversion, as do components and prop

In the DOM, when adding a custom event listener to a component, it is recommended to use the kebab-case naming method for the event name and also distribute the kebab-case

As in the previous example 🌰

If used in a string template, it can be either hump or kebab-case nomenclature

Verify the event

Validating events is similar to validating prop, except that the former uses emits and the latter uses props

The value of the emits option can be an object in which each attribute name represents the event name and the value of the attribute represents the event-related validation

Correlation validation is usually a function that automatically accepts the parameters of the event it listens for. The main purpose of a validation event is to verify that the parameters passed by the event are compliant

For example 🌰 : To validate the my-event event, you must pass in two parameters

[Vue WARN]: Invalid Event arguments: [Vue warn]: Invalid Event arguments: event validation failed for event “my-event”.

The validation function eventually returns a Boolean value indicating whether the event is valid

V-model on component

V – the parameters of the model

By default, V-models on components use modelValue as prop and Update :modelValue as events

ModelValue can be modified by v-model parameters, such as V-Model: XXX

The new event name changes to update: XXX

For example 🌰 : The following event name becomes update:my-title instead of the default update:modelValue

Multiple V-Model bindings

Multiple V-Model bindings can be created on a single component instance

Each V-Model will be synchronized to a different prop without the need to add additional options to the component

In fact, with a single V-model no difference, here is not an example 🌰

Handle v-Model modifiers

The built-in modifiers for v-model are. Trim,. Number, and.lazy, which remove whitespace, make it a number, and make it a lazy mode, respectively

It is very simple to add it directly after v-model or after its modifier, for example 🌰 : remove the Spaces around title

You can customize modifiers for V-models in Vue3 via modelModifiers

For V-Model bindings with parameters, the generated prop names will be arG + “Modifiers”

Example 🌰 : Customize a capitalize modifier that capitalizes the first letter

<div id="app">
    <my-component v-model.capitalize='title'></my-component>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
    const { createApp } = Vue
    const MyComponent = {
        template: '<input @input="onInput" :value="modelValue" />'.emits: ['update:mode-value'].props: {
            modelValue: {
                type: String.default: ' '
            },
            modelModifiers: {
                default: () = >({})}},methods: {
            onInput(e) {
                let val = e.target.value
                if (this.modelModifiers.capitalize) {
                    val = val.charAt(0).toUpperCase() + val.slice(1)
                    console.log(val);
                }
                this.$emit('update:mode-value', val)
            }
        }
    }
    const app = createApp({
        data() {
            return {
                title: 'V-model modifier'}},components: { 'my-component': MyComponent }
    })
    app.mount('#app');
</script>
Copy the code

summary

For convenience, I’ve grouped the content related to custom events into one diagram

END

To facilitate bulk download, the original brain map is uploaded to GitHub:

Github.com/jCodeLife/m…

If you have any other questions, please leave a comment