Components Basics

Base Example

Here’s an example of a Vue component:

  1. // Create a Vue application
  2. const app = Vue.createApp({})
  3. // Define a new global component called button-counter
  4. app.component('button-counter', {
  5. data() {
  6. return {
  7. count: 0
  8. }
  9. },
  10. template: `
  11. <button v-on:click="count++">
  12. You clicked me {{ count }} times.
  13. </button>`
  14. })

Components are reusable Vue instances with a name: in this case, <button-counter>. We can use this component as a custom element inside a root Vue instance:

  1. <div id="components-demo">
  2. <button-counter></button-counter>
  3. </div>
  1. app.mount('#components-demo')

See the Pen Component basics by Vue (@Vue) on CodePen.

Since components are reusable Vue instances, they accept the same options as a root instance, such as data, computed, watch, methods, and lifecycle hooks. The only exceptions are a few root-specific options like el.

Reusing Components

Components can be reused as many times as you want:

  1. <div id="components-demo">
  2. <button-counter></button-counter>
  3. <button-counter></button-counter>
  4. <button-counter></button-counter>
  5. </div>

See the Pen Component basics: reusing components by Vue (@Vue) on CodePen.

Notice that when clicking on the buttons, each one maintains its own, separate count. That’s because each time you use a component, a new instance of it is created.

Organizing Components

It’s common for an app to be organized into a tree of nested components:

Component Tree

For example, you might have components for a header, sidebar, and content area, each typically containing other components for navigation links, blog posts, etc.

To use these components in templates, they must be registered so that Vue knows about them. There are two types of component registration: global and local. So far, we’ve only registered components globally, using component method of created app:

  1. const app = Vue.createApp({})
  2. app.component('my-component-name', {
  3. // ... options ...
  4. })

Globally registered components can be used in the template of app instance created afterwards - and even inside all subcomponents of that Vue instance’s component tree.

That’s all you need to know about registration for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Component Registration.

Passing Data to Child Components with Props

Earlier, we mentioned creating a component for blog posts. The problem is, that component won’t be useful unless you can pass data to it, such as the title and content of the specific post we want to display. That’s where props come in.

Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance. To pass a title to our blog post component, we can include it in the list of props this component accepts, using a props option:

  1. const app = Vue.createApp({})
  2. app.component('blog-post', {
  3. props: ['title'],
  4. template: `<h4>{{ title }}</h4>`
  5. })
  6. app.mount('#blog-post-demo')

A component can have as many props as you’d like and by default, any value can be passed to any prop. In the template above, you’ll see that we can access this value on the component instance, just like with data.

Once a prop is registered, you can pass data to it as a custom attribute, like this:

  1. <div id="blog-post-demo" class="demo">
  2. <blog-post title="My journey with Vue"></blog-post>
  3. <blog-post title="Blogging with Vue"></blog-post>
  4. <blog-post title="Why Vue is so fun"></blog-post>
  5. </div>

See the Pen Component basics: passing props by Vue (@Vue) on CodePen.

In a typical app, however, you’ll likely have an array of posts in data:

  1. const App = {
  2. data() {
  3. return {
  4. posts: [
  5. { id: 1, title: 'My journey with Vue' },
  6. { id: 2, title: 'Blogging with Vue' },
  7. { id: 3, title: 'Why Vue is so fun' }
  8. ]
  9. }
  10. }
  11. }
  12. const app = Vue.createApp()
  13. app.component('blog-post', {
  14. props: ['title'],
  15. template: `<h4>{{ title }}</h4>`
  16. })
  17. app.mount('#blog-posts-demo')

Then want to render a component for each one:

  1. <div id="blog-posts-demo">
  2. <blog-post
  3. v-for="post in posts"
  4. :key="post.id"
  5. :title="post.title"
  6. ></blog-post>
  7. </div>

Above, you’ll see that we can use v-bind to dynamically pass props. This is especially useful when you don’t know the exact content you’re going to render ahead of time.

That’s all you need to know about props for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Props.

Listening to Child Components Events

As we develop our <blog-post> component, some features may require communicating back up to the parent. For example, we may decide to include an accessibility feature to enlarge the text of blog posts, while leaving the rest of the page its default size.

In the parent, we can support this feature by adding a postFontSize data property:

  1. const App = {
  2. data() {
  3. return {
  4. posts: [
  5. /* ... */
  6. ],
  7. postFontSize: 1
  8. }
  9. }
  10. }

Which can be used in the template to control the font size of all blog posts:

  1. <div id="blog-posts-events-demo">
  2. <div v-bind:style="{ fontSize: postFontSize + 'em' }">
  3. <blog-post v-for="post in posts" :key="post.id" :title="title"></blog-post>
  4. </div>
  5. </div>

Now let’s add a button to enlarge the text right before the content of every post:

  1. app.component('blog-post', {
  2. props: ['title'],
  3. template: `
  4. <div class="blog-post">
  5. <h4>{{ title }}</h4>
  6. <button>
  7. Enlarge text
  8. </button>
  9. </div>
  10. `
  11. })

The problem is, this button doesn’t do anything:

  1. <button>
  2. Enlarge text
  3. </button>

When we click on the button, we need to communicate to the parent that it should enlarge the text of all posts. Fortunately, Vue instances provide a custom events system to solve this problem. The parent can choose to listen to any event on the child component instance with v-on or @, just as we would with a native DOM event:

  1. <blog-post ... @enlarge-text="postFontSize += 0.1"></blog-post>

Then the child component can emit an event on itself by calling the built-in $emit method, passing the name of the event:

  1. <button @click="$emit('enlarge-text')">
  2. Enlarge text
  3. </button>

Thanks to the v-on:enlarge-text="postFontSize += 0.1" listener, the parent will receive the event and update postFontSize value.

See the Pen Component basics: emitting events by Vue (@Vue) on CodePen.

Emitting a Value With an Event

It’s sometimes useful to emit a specific value with an event. For example, we may want the <blog-post> component to be in charge of how much to enlarge the text by. In those cases, we can use $emit‘s 2nd parameter to provide this value:

  1. <button @click="$emit('enlarge-text', 0.1)">
  2. Enlarge text
  3. </button>

Then when we listen to the event in the parent, we can access the emitted event’s value with $event:

  1. <blog-post ... @enlarge-text="postFontSize += $event"></blog-post>

Or, if the event handler is a method:

  1. <blog-post ... @enlarge-text="onEnlargeText"></blog-post>

Then the value will be passed as the first parameter of that method:

  1. methods: {
  2. onEnlargeText(enlargeAmount) {
  3. this.postFontSize += enlargeAmount
  4. }
  5. }

Using v-model on Components

Custom events can also be used to create custom inputs that work with v-model. Remember that:

  1. <input v-model="searchText" />

does the same thing as:

  1. <input :value="searchText" @input="searchText = $event.target.value" />

When used on a component, v-model instead does this:

  1. <custom-input
  2. :model-value="searchText"
  3. @update:model-value="searchText = $event"
  4. ></custom-input>

WARNING

Please note we used model-value with kebab-case here because we are working with in-DOM template. You can find a detailed explanation on kebab-cased vs camelCased attributes in the DOM Template Parsing Caveats section

For this to actually work though, the <input> inside the component must:

  • Bind the value attribute to a modelValue prop
  • On input, emit an update:modelValue event with the new value

Here’s that in action:

  1. app.component('custom-input', {
  2. props: ['modelValue'],
  3. template: `
  4. <input
  5. :value="modelValue"
  6. @input="$emit('update:modelValue', $event.target.value)"
  7. >
  8. `
  9. })

Now v-model should work perfectly with this component:

  1. <custom-input v-model="searchText"></custom-input>

That’s all you need to know about custom component events for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Custom Events.

Content Distribution with Slots

Just like with HTML elements, it’s often useful to be able to pass content to a component, like this:

  1. <alert-box>
  2. Something bad happened.
  3. </alert-box>

Which might render something like:

See the Pen Component basics: slots by Vue (@Vue) on CodePen.

Fortunately, this task is made very simple by Vue’s custom <slot> element:

  1. app.component('alert-box', {
  2. template: `
  3. <div class="demo-alert-box">
  4. <strong>Error!</strong>
  5. <slot></slot>
  6. </div>
  7. `
  8. })

As you’ll see above, we just add the slot where we want it to go — and that’s it. We’re done!

That’s all you need to know about slots for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Slots.

Dynamic Components

Sometimes, it’s useful to dynamically switch between components, like in a tabbed interface:

See the Pen Component basics: dynamic components by Vue (@Vue) on CodePen.

The above is made possible by Vue’s <component> element with the is special attribute:

  1. <!-- Component changes when currentTabComponent changes -->
  2. <component :is="currentTabComponent"></component>

In the example above, currentTabComponent can contain either:

  • the name of a registered component, or
  • a component’s options object

See this sandboxComponents Basics - 图2 to experiment with the full code, or this versionComponents Basics - 图3 for an example binding to a component’s options object, instead of its registered name.

Keep in mind that this attribute can be used with regular HTML elements, however they will be treated as components, which means all attributes will be bound as DOM attributes. For some properties such as value to work as you would expect, you will need to bind them using the .prop modifier.

That’s all you need to know about dynamic components for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Dynamic & Async Components.

DOM Template Parsing Caveats

Some HTML elements, such as <ul>, <ol>, <table> and <select> have restrictions on what elements can appear inside them, and some elements such as <li>, <tr>, and <option> can only appear inside certain other elements.

This will lead to issues when using components with elements that have such restrictions. For example:

  1. <table>
  2. <blog-post-row></blog-post-row>
  3. </table>

The custom component <blog-post-row> will be hoisted out as invalid content, causing errors in the eventual rendered output. Fortunately, we can use v-is special directive as a workaround:

  1. <table>
  2. <tr v-is="'blog-post-row'"></tr>
  3. </table>

WARNING

v-is value should be a JavaScript string literal:

  1. <!-- Incorrect, nothing will be rendered -->
  2. <tr v-is="blog-post-row"></tr>
  3. <!-- Correct -->
  4. <tr v-is="'blog-post-row'"></tr>

Also, HTML attribute names are case-insensitive, so browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names and event handler parameters need to use their kebab-cased (hyphen-delimited) equivalents:

  1. // camelCase in JavaScript
  2. app.component('blog-post', {
  3. props: ['postTitle'],
  4. template: `
  5. <h3>{{ postTitle }}</h3>
  6. `
  7. })
  1. <!-- kebab-case in HTML -->
  2. <blog-post post-title="hello!"></blog-post>

It should be noted that these limitations does not apply if you are using string templates from one of the following sources:

That’s all you need to know about DOM template parsing caveats for now - and actually, the end of Vue’s Essentials. Congratulations! There’s still more to learn, but first, we recommend taking a break to play with Vue yourself and build something fun.

Once you feel comfortable with the knowledge you’ve just digested, we recommend coming back to read the full guide on Dynamic & Async Components, as well as the other pages in the Components In-Depth section of the sidebar.