SoFunction
Updated on 2025-04-05

Component usage development example tutorial

Components

Components can extend HTML elements and encapsulate reusable code. At a higher level, components are custom elements, and the compiler adds special features to it. In some cases, components can also be in the form of native HTML elements, extending in the is feature.

The component can be understood as a ViewModel class with predefined behavior. A component can predefined many options, but the most important ones are the following:

template: The template declares the mapping relationship between the data and the DOM that is finally presented to the user.

Initial data: The initial data state of a component. This is usually a private state for reusable components.

Accepted external parameters (props): Data is passed and shared between components through parameters. The parameters are unidirectional binding by default (from top to bottom), but can also be explicitly declared as bidirectional binding.

Methods: Changes to data are generally carried out within the component's methods. User input events and component methods can be bound through the v-on directive.

Lifecycle hooks: A component will trigger multiple lifecycle hooks, such as created, attached, destroyed, etc. In these hook functions, we can encapsulate some custom logic. Compared with traditional MVC, it can be understood that the logic of the Controller is scattered into these hook functions.

Private resources: User-defined instructions, filters, components, etc. are collectively referred to as resources. Since global registration of resources can easily lead to naming conflicts, a component can declare its own private resources. Only this component and its subcomponents can be called for a private resource.

In addition, components within the same component tree can also communicate through the built-in event API. It provides a complete API for defining, reusing and nesting components, allowing developers to spell out the entire application interface with components like building blocks.

Components greatly improve code efficiency, maintenance and reuse rate.

Usage Components

register

1. Create a component constructor:

var MyComponent = ({
//Options})

2. Use the constructor as a component and register with (tag, constructor):

('my-component',MyComponent)

3. Use it in the module of the parent instance as a custom element <my-component>:

<div id = "example">
<my-component></my-component>
</div>

example:

&lt;div &gt;
&lt;my-component&gt;&lt;/my-component&gt;
&lt;/div&gt;
// Definitionvar MyComponent = ({
template: '&lt;div&gt;A custom component!&lt;/div&gt;'
})
// register('my-component', MyComponent)
// Create a root instancenew Vue({
el: '#example'
})

Rendered as:

<div id = "example">
<div>A custom component!</div>
</div>

The template of the component replaces the custom element, and the function of the custom element is only as a mount point. You can use the instance option replace to decide whether to replace it.

Local registration

Register with the instance option components, and does not require global registration of each component, so that the component can only be used in other components:

var Child = ({ /* ... */ })
var Parent = ({
template: '...',
components: {
// <my-component> can only be used in parent component templates'my-component': Child
}
})

This encapsulation is also suitable for other resources such as instructions, filters, and transitions.

Register syntactic sugar

// Extend and register in one step('my-component', {
template: '&lt;div&gt;A custom component!&lt;/div&gt;'
})
// This is also possible with local registrationvar Parent = ({
components: {
'my-component': {
template: '&lt;div&gt;A custom component!&lt;/div&gt;'
}
}
})

Component Options Issues

Most options passed into the Vue constructor can also be used in (). In addition to data and el, if an object is simply passed to () as a data option, all instances will share the same data object. Therefore, we should use a function as a data option to let this function return a new object:

var MyComponent = ({
data: function () {
return { a: 1 }
}
})

Template analysis

Vue's template is a DOM template, which uses a browser native parser, so it must be a valid HTML snippet. Some HTML elements have restrictions on what elements can be placed in it. Common restrictions are:

a cannot contain other interactive elements (such as buttons, links)

ul and ol can only directly contain li

select can only contain option and optgroup

table can only directly contain thead, tbody, tfoot, tr, caption, col, colgroup

tr can only contain th and td directly

In practice, these limitations can lead to unexpected results. Although it may work in simple cases, you cannot rely on custom components to expand results before browser validation. For example

<my-select><option>...</option></my-select> is not a valid template, even if the my-select component ends up expanding to <select>...</select>.

Another result is that custom tags (including custom elements and special tags, such as <component>, <template>, <partial>) cannot be used in tags such as ul, select, table, etc. that have restrictions on internal elements. Custom tags placed inside these elements will be mentioned outside the element, thus rendering incorrectly.

For custom elements, the is attribute should be used:

<table>

&lt;tr is="my-component"&gt;&lt;/tr&gt;
&lt;/table&gt;
//<template> cannot be used in <table>. At this time, <tbody> should be used. <table> can have multiple <tbody>&lt;table&gt;
&lt;tbody v-for="item in items"&gt;
&lt;tr&gt;Even row&lt;/tr&gt;
&lt;tr&gt;Odd row&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

Props

Passing data using props

The scope of component instances is isolated. You can use props to pass arrays to child components. Props is a field of component data. It is expected to pass it down from the parent component. The child components need to explicitly declare props with the props option:

('child', {
// Statement propsprops: ['msg'],
// prop can be used in templates// Can be set using ``template: '&lt;span&gt;{{ msg }}&lt;/span&gt;'
})

Then pass it a normal string:

<child msg="hello!"></child>

Dynamic props

Use v-bind to bind dynamic props to the parent component's data. Whenever the parent component's data changes, it will also be transmitted to the child component:

<div>
<input v-model="parentMsg">
<child v-bind:my-message="parentMsg"></child>
//<child :my-message="parentMsg"></child>
</div>

Props binding type

Prop is a one-way binding by default. When the properties of the parent component change, it will be passed to the child component, but in turn will not. This is to prevent the child component from accidentally modifying the state of the parent component. You can explicitly force bidirectional or single-time binding using the .sync or .once binding modifier:

&lt;!-- Default is one-way binding --&gt;
&lt;child :msg="parentMsg"&gt;&lt;/child&gt;
&lt;!-- Two-way binding --&gt;
&lt;child :="parentMsg"&gt;&lt;/child&gt;
&lt;!-- Single binding --&gt;
&lt;child :="parentMsg"&gt;&lt;/child&gt;

If prop is an object or array, it is passed by reference. Modifying it within a child component will affect the state of the parent component, regardless of the binding type used.

Parent-child component communication

Parent link

The child component can access its parent component with this.$parent, and the descendants of the root instance can access it with this.$root. The parent component has an array this.$children, which contains all its child elements.

Custom events

Vue instances implement a custom event interface for communication in the component tree. This event system is independent of native DOM events and has different usages. Each Vue instance is an event trigger:

Use $on() to listen for events;

Use $emit() to trigger an event on it;

Use $dispatch() to dispatch events, and the events bubble along the parent chain;

Use $broadcast() to broadcast events, and events are transmitted downwards to all descendants.

Unlike the DOM event, the Vue event automatically stops bubble after the first callback is triggered during the bubble process, unless the callback explicitly returns true.

&lt;!-- Subcomponent template --&gt;
&lt;template &gt;
&lt;input v-model="msg"&gt;
&lt;button v-on:click="notify"&gt;Dispatch Event&lt;/button&gt;
&lt;/template&gt;
&lt;!-- Parent component template --&gt;
&lt;div &gt;
&lt;p&gt;Messages: {{ messages | json }}&lt;/p&gt;
&lt;child&gt;&lt;/child&gt;
&lt;/div&gt;
// Register subcomponents// Send the current message('child', {
template: '#child-template',
data: function () {
return { msg: 'hello' }
},
methods: {
notify: function () {
if (()) {
this.$dispatch('child-msg', )
 = ''
}
}
}
})
// Initialize the parent component// Push the event into an array when the message is receivedvar parent = new Vue({
el: '#events-example',
data: {
messages: []
},
// The `events` option simply calls `$on` when creating an instanceevents: {
'child-msg': function (msg) {
// The `this` in the event callback is automatically bound to the instance that registered it(msg)
}
}
})

Effect:

Use v-on to bind custom events

Declare the event handler where subcomponents are used in the template. For this subcomponents can use v-on to listen for custom events:

<child v-on:child-msg="handleIt"></child>

When the child component triggers the "child-msg" event, the parent component's handleIt method will be called. All code that affects the state of the parent component is placed in the handleIt method of the parent component; the child component only focuses on the triggering event.

Subcomponent index

Use v-ref to specify an index ID for the child component, and you can directly access the child component

&lt;div &gt;
&lt;user-profile v-ref:profile&gt;&lt;/user-profile&gt;
&lt;/div&gt;
var parent = new Vue({ el: '#parent' })
// Access subcomponentsvar child = parent.$

Distribute content using Slot

Content distribution: A way to mix the parent component's content with the child component's own template, using a special <slot> element as a slot for the original content.

Compile scope

The contents of the parent component template are compiled within the scope of the parent component; the contents of the child component template are compiled within the scope of the child component.

Bind instructions within a subcomponent to the root node of a component:

('child-component', {
// works because it is within the correct scopetemplate: '&lt;div v-show="someChildProperty"&gt;Child&lt;/div&gt;',
data: function () {
return {
someChildProperty: true
}
}
})

Similarly, the distribution content is compiled within the scope of the parent component.

Single slot

The contents of the parent component will be discarded unless the child component template contains <slot>, if the child component template has only one slot without characteristics, the entire contents of the parent component will be inserted where the slot is and replace it.

The content of the <slot> tag is considered to be rollback content. The fallback content is compiled within the scope of the child component, and the fallback content is displayed when the host element is empty and there is no content for insertion.

Assume that the my-component component has the following template:

<div>
<h1>This is my component!</h1>
<slot>

If there is no distribution, I will be displayed.

</slot>
</div>

Parent component template:

<my-component>
<p>This is some original content</p>
<p>This is some more original content</p>
</my-component>

Rendering result:

<div>
<h1>This is my component!</h1>
<p>This is some original content</p>
<p>This is some more original content</p>
</div>

Named slot

The <slot> element can be configured with a special feature name to configure how to distribute content. Multiple slots can have different names. A named slot will match the elements with corresponding slot characteristics in the content fragment.

There can still be an anonymous slot, which is the default slot, as a fallback slot for matching content fragments that cannot be found. Without a default slot, these unmatched content fragments will be discarded.

Dynamic Components

Multiple components can use the same mount point, then dynamically switch between them, using the reserved <component> element, dynamically bind to its is feature:

new Vue({
el: 'body',
data: {
currentView: 'home'
},
components: {
home: { /* ... */ },
posts: { /* ... */ },
archive: { /* ... */ }
}
})
&lt;component :is="currentView"&gt;
&lt;!-- The components are in  Change when changes --&gt;
&lt;/component&gt;

keep-alive

Keeping the switched component in memory can preserve its state or avoid re-rendering.

<component :is="currentView" keep-alive>
<!-- Inactive components will be cached -->
</component>

activate hook

Controls the duration of component switching. The activate hook only acts during dynamic component switching or static component initialization rendering, and does not act in manual insertion using instance methods.

('activate-example', {
activate: function (done) {
var self = this
loadDataAsync(function (data) {
 = data
done()
})
}
})

transition-mode

The transition-mode feature is used to specify how two dynamic components transition.

By default, enter and leave transition smoothly. This feature can specify two other modes:

in-out: The new component first transitions into, and after its transition is completed, the current component will transition out.

out-in: The current component first transitions out, and after its transition is completed, the new component transitions into the process.

Example:

&lt;!-- Fade out first and then fade in --&gt;
&lt;component
:is="view"
transition="fade"
transition-mode="out-in"&gt;
&lt;/component&gt;
.fade-transition {
transition: opacity .3s ease;
}
.fade-enter, .fade-leave {
opacity: 0;
}

The Component API comes from three parts—prop, events and slot:

prop allows the external environment to pass data to components;

Events Allow components to trigger actions of external environments;

slot allows the external environment to insert content into the component's view structure.

The above is the component usage and development example tutorial introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!