Component concept
A component is a reusable, maintainable, and easily composed piece of code. In a Vue, a component is actually an instance of a Vue. Packaging some relatively independent modules into components is very useful for code reuse and maintenance.
The component registration
- The component named
Component names will be used in templates like HTML tags in the future, so it is best not to conflict with native tags or may conflict in the future. Therefore, the official naming method is all lowercase and must contain a hyphen, for example:
Vue.component("v-component-name", {/ /...
template:`
//....
`
});
Copy the code
- Global registration
There are components that we expect to use everywhere on the Web that we need to use globally, so we can write once and use anywhere.
Vue.component('component-a', { /* ... */ })
Copy the code
- Local registration
Sometimes we may only use this component for specific business purposes and do not want to register this component globally. At this point, local registration can be performed as follows.
var ComponentA = {
/ *... * /
};
new Vue({
el: "#app".components: {
"component-a": ComponentA,
},
});
Copy the code
Component life cycle
A component is an instance of a Vue. During the creation and destruction of the Vue instance, Vue implements a series of hook functions that are automatically executed at certain times.
-
Create a stage
beforeCreate
Do some initialization before the function is executed, such as initializing the default properties and events of the instance, but nothing related to the state is initialized, which means you can’t call the props, methods, data, computed, watch, etc
created
After executing beforeCreate, Vue will immediately give us the initialization state method and so on. In this method you can usually get props, data, and other related state properties or methods passed
-
Mount the stage
beforeMount
The render function is generated by analyzing your options before mounting them to the page to determine if there is an EL or template
mounted
Actually mount the page to generate the real DOM. In this method, you can easily get the DOM you want to manipulate
-
Update the stage
beforeUpdate
When the data you rely on in your template changes, but the virtual Dom has not been re-rendered and patched
updated
When the virtual Dom has been re-rendered and the interface has changed
-
Destruction of phase
beforeDestroy
Called before the component is destroyed, when the component is still available. This is a good place to clear event bindings for timer tasks or Windows
destroyed
All event listeners are removed and all subinstances are destroyed
Component Properties Prop
A component can be thought of as a custom tag, so it should also have properties that are passed in from the outside for functions. Prop is usually passed inside a component statically or by data binding where the component is used. The component then receives these incoming values internally via a props property. Such as:
<div id="app">
<my-component title="123" color="red" userName="userName"></my-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script></script>
Copy the code
The only thing to note here is that it is recommended to use lowercase or dash names when binding properties, mainly because browsers are case-insensitive to property names. Any type of value can be passed to a child component as a property
- Unidirectional data flow
In componential development, one of the norms is to follow a one-way flow of data, meaning that the parent component’s data is passed to the child component, and the child component should be read-only and should not attempt to change it, although it is possible to do so, but not recommended. If you really want to use this, you can assign props to data or computed. However, it is important to be aware of reference types, so it is generally not recommended that child components change props.
- Props to verify
Props are passed to sub-components as data. As a strict programmer, we sometimes need to make type or value decisions on the data to make components more robust. Props can also be an object to type check each passed property. A standard property check format is as follows:
props: {
// Test type + other validations
age: {
type: Number.String, Number, Boolean, Array, Object, Date, Function, Symbol
default: 0.// any
required: true.// boolean
validator: function (value) {
// todo}}}Copy the code
The console throws a warning when an incoming value does not comply with validation!
- No properties received by props
Sometimes you might write custom properties where components are used, or you might write the wrong properties that are not received inside the component via props. By default, these attributes will be inherited to the outermost root tag of your component. Sometimes mistakes can be made. Such as:
/ / use
<my-input class="def" type="button" data-hello="hello"></my-input>;
// Declare the component
Vue.component("my-input", {
template: '.inheritAttrs: false.// Do not inherit, that is, the attributes used above do not inherit to the input tag, if enabled will break the tag.
mounted() {
console.log(this.$attrs); }});Copy the code
Note that these properties, which are not accepted by prop, reside on the component instance’s $attrs. In additionclass
& style
The attributes of the
Component custom events
Custom events are actually events that you define on your custom component, and then the component fires those events at some point in the form of consumption.
// Bind events
<my-component v-on:my-event="doSomething"></my-component>;
// Consumption events
this.$emit("my-event". args);Copy the code
For details about custom events, see the documentation custom Events
Dynamic and asynchronous components
- Dynamic components
A dynamic component, as the name implies, is a component that can become another component at some point in the future, and if we don’t pass a dynamic component, maybe you have to control the display and hide of the component yourself. For example, we divide the page into 10 blocks, but these 10 blocks are also 10 components, but these 10 components may be arranged differently depending on the date and time. What about features like this? Suppose you have an interface that conditionally returns to you which components should be displayed each day
{
code:0.data: ['component-a'.'component-b']}Copy the code
You can do this in a loop, using dynamic components that Vue provides. Component is the built-in component that Vue provides to us
<component v-bind:is="item" v-for="item of componentList"></component>
Copy the code
Sometimes you may need to switch components dynamically, but each switch will re-render the original component. You may need to use the keep-alive component at this point.
- Asynchronous components
Asynchronous component is a kind of component only when the real use of the component will load the resources required by the component, so as to better do code segmentation and performance optimization, speed up the first screen speed; Vue fires the factory function only when the component needs to be rendered, and caches the result for future re-rendering. In fact, the second argument to defining a component can be a function in addition to passing an object.
Vue.component('async-example'.function (resolve, reject) {
setTimeout(function () {
// Pass the component definition to the 'resolve' callback
resolve({
template: '
I am async!
'})},1000)})Copy the code
You can also declare components like this:
Vue.component(
'async-webpack-example'.// This dynamic import returns a 'Promise' object.
() = > import('./my-async-component'))Copy the code
Or local declaration
new Vue({
// ...
components: {
'my-component': () = > import('./my-async-component')}})Copy the code
In other cases, your method may need to request an interface and handle some exceptions, in which case you may need to define the exception handling problem:
const AsyncComponent = () = > ({
// todo something
// The component to load (should be a 'Promise' object)
component: import('./MyComponent.vue'),
// The component used when the asynchronous component is loaded
loading: LoadingComponent,
// The component used when loading failed
error: ErrorComponent,
// Display the component delay time when loading. The default is 200 (ms)
delay: 200.// If a timeout is provided and the component loads time out,
// Use the component used when the load failed. The default value is' Infinity '
timeout: 3000
})
Copy the code
See dynamic Components & Asynchronous components for details
slot
Component custom V-model and slot
Component communication
Component communication is a very important part of component communication, and some common component communication methods will be summarized in the following articles