search
HomeWeb Front-endJS TutorialA Beginner's Guide to Working With Components in Vue

A Beginner’s Guide to Working With Components in Vue

Vue.js' component architecture makes building a user interface efficient and convenient. It allows you to break down your application into smaller, reusable components and then build more complex structures with these components.

This guide will provide you with an advanced introduction to Vue components. We will explore how to create components, how to pass data between components (via props and event buses), and how to render additional content within components using Vue's <slot></slot> element. Each example will come with a runnable CodePen demo.

Key Points

  • Vue's componentized architecture helps break down the UI into reusable, easy-to-manage snippets, thereby enhancing the reusability and organization of the code.
  • Components can be created globally using Vue.component or locally in single-file components. For complex projects, the latter is more suitable for use because of its encapsulation of templates, scripts, and styles.
  • The data can be passed to subcomponents using props, providing a clear and structured way to manage and pass data in the component tree.
  • The event bus can be used to effectively manage communication from child components to parent components, allowing child components to send data back to the component hierarchy.
  • Vue's <slot></slot> element helps nest content within the component, making it more flexible and able to receive content from the parent component, which can be overwritten with fallback content.

How to create components in Vue

Components are essentially reusable Vue instances with names. There are many ways to create components in a Vue application. For example, in small to medium-sized projects, you can register global components using the Vue.component method as follows:

Vue.component('my-counter', {
  data() {
    return {
      count: 0
    }
  },
  template: `<div>{{ count }}</div>`
})

new Vue({ el: '#app' })
The name of the

component is my-counter. It can be used like this:

<div>
  <my-counter></my-counter>
</div>
When naming a component, you can choose to use kebab-case (

) or Pascal-case (my-custom-component). When referencing components in templates, either variant can be used, but when referencing components directly in the DOM (as shown in the above example), only the MyCustomComponent kebab-case tag name is valid. You may also notice that in the above example,

is a function that returns the object literal (rather than the object literal itself). The purpose of this is to let each instance of the component have its own data object without having to share a global instance with all other instances.

data There are several ways to define component templates. Above we used template literals, but we can also use markers with

or templates inside the DOM. You can read more about the different ways to define templates here.

text/x-template

Single file component

In more complex projects, global components can quickly become difficult to manage. In this case, it makes sense to design your application to use a single file component. As the name implies, these are single files with .vue extensions that contain <template></template>,

And the MyCounter component may look like this:
Vue.component('my-counter', {
  data() {
    return {
      count: 0
    }
  },
  template: `<div>{{ count }}</div>`
})

new Vue({ el: '#app' })

As you can see, when using single file components, you can import and use them directly in the components that require them.

Vue.component() In this guide, I will use the

method to register the component to show all the examples.

Using single-file components often involves building steps (for example, using Vue CLI). If you want to learn more, check out the "Vue CLI Getting Started Guide" in this Vue series.

Transfer data to components via Props

Props enables us to pass data from parent component to child component. This allows our components to be divided into smaller chunks to handle specific functions. For example, if we have a blog component, we might want to display information such as author details, post details (title, body, and image), and comments.

We can break these into child components so that each component processes specific data, making the component tree look like this:
<div>
  <my-counter></my-counter>
</div>

If you still don't believe in the benefits of using components, take a moment to realize how useful this combination is. If you want to revisit this code in the future, you will immediately be clear on how the page is built and where you should look for which functionality (i.e. in which component). This declarative way of combining interfaces also makes it easier for those who are not familiar with the code base to get started quickly and improve efficiency.

Since all data will be passed from the parent component, it might look like this:
<template>
  <div>{{ count }}</div>
</template>

<🎜>

author-detailIn the above example component, we define the author details and post information. Next, we have to create the child components. Let's name the child component

. Therefore, our HTML template will look like this:
<blogpost>
  <authordetails></authordetails>
  <postdetails></postdetails>
  <comments></comments>
</blogpost>

ownerWe pass the author object to the child component as props named owner. There is a need to pay attention to the difference here. In a child component, author is the props name that we receive data from the parent component. The data we want to receive is called

, which we define in the parent component.

author-detailTo access this data, we need to declare props in the

component:
new Vue({
  el: '#app',
  data() {
    return {
      author: {
        name: 'John Doe',
        email: 'jdoe@example.com'
      }
    }
  }
})

We can also enable verification when passing props to ensure the correct data is passed. This is similar to PropTypes in React. To enable verification in the example above, change our component to look like this:
<div>
  <author-detail :owner="author"></author-detail>
</div>

If we pass the wrong prop type, you will see an error in the console similar to what I've shown below:
Vue.component('author-detail', {
  template: `
    <div>
      <h2 id="owner-name">{{ owner.name }}</h2>
      <p>{{ owner.email }}</p>
    </div>
  `,
  props: ['owner']
})

There is an official guide in the Vue documentation that you can use to understand prop verification.

Communication from child component to parent component via event bus

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version