Table of Contents
{{ owner.name }}
Home Web Front-end JS Tutorial A Beginner's Guide to Working With Components in Vue

A Beginner's Guide to Working With Components in Vue

Feb 14, 2025 am 09:35 AM

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' })</pre>
Copy after login
Copy after login
Copy after login
The name of the

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

<div>
  <my-counter></my-counter>
</div></pre>
Copy after login
Copy after login
Copy after login
Copy after login
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>, </pre>

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

new Vue({ el: '#app' })</pre>
Copy after login
Copy after login
Copy after login

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></pre>
Copy after login
Copy after login
Copy after login
Copy after login

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>

<🎜></pre>
Copy after login
Copy after login
Copy after login

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></pre>
Copy after login
Copy after login
Copy after login

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'
      }
    }
  }
})</pre>
Copy after login
Copy after login

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></pre>
Copy after login
Copy after login

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']
})</pre>
Copy after login
Copy after login

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

<script></code> 和 <code>&lt;style&gt;</code> 部分。</p> <p>对于上面的示例,App 组件可能如下所示:</p> <pre class="brush:php;toolbar:false"><code class="vue">&lt;template&gt; <div> <my-counter></my-counter> </div> </template> <script> import myCounter from './components/myCounter.vue' export default { name: 'app', components: { myCounter } } </script>

Events are handled by creating wrapper methods that are triggered when the selected event occurs. To review, let's expand based on our initial counter example so that it increases every time the button is clicked.

Our components should look like this:

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

new Vue({ el: '#app' })</pre>
Copy after login
Copy after login
Copy after login

and our template:

<div>
  <my-counter></my-counter>
</div></pre>
Copy after login
Copy after login
Copy after login
Copy after login

This hope is simple enough. As you can see, we are connecting to the onClick event to trigger a custom increase method every time the button is clicked. The increase method then increments our count data attributes. Now let's expand the example, move the counter button into a separate component and display the count in the parent component. We can do this using event bus.

Event bus is very convenient when you want to communicate from child components to parent components. This is contrary to the default communication method, which is from the parent component to the child component. If your application isn't big enough to not need Vuex, you can use the event bus. (You can read more about it in the "Vuex Getting Started Guide" in this Vue series.)

So what we have to do is: the count will be declared in the parent component and passed down to the child component. Then in the child component, we want to increment the value of count and make sure that the value in the parent component is updated.

App components will look like this:

<template>
  <div>{{ count }}</div>
</template>

<🎜></pre>
Copy after login
Copy after login
Copy after login

Then in the child component, we want to receive the count through props and have a way to increment it. We do not want to display the value of count in the child component. We just want to increment from the child component and make it reflect in the parent component:

<blogpost>
  <authordetails></authordetails>
  <postdetails></postdetails>
  <comments></comments>
</blogpost></pre>
Copy after login
Copy after login
Copy after login

Then our template will look like this:

new Vue({
  el: '#app',
  data() {
    return {
      author: {
        name: 'John Doe',
        email: 'jdoe@example.com'
      }
    }
  }
})</pre>
Copy after login
Copy after login

If you try to increment the value like that, it won't work. In order for it to work, we have to issue an event from the child component, send a new value of count, and also listen for this event in the parent component.

First, we create a new Vue instance and set it to eventBus:

<div>
  <author-detail :owner="author"></author-detail>
</div></pre>
Copy after login
Copy after login

We can now use event bus in our components. The subcomponent will look like this:

Vue.component('author-detail', {
  template: `
    <div>
      <h2 id="owner-name">{{ owner.name }}</h2>
      <p>{{ owner.email }}</p>
    </div>
  `,
  props: ['owner']
})</pre>
Copy after login
Copy after login

Events every time the increment method is called. We have to listen for the event in the main component and set count to the value we get from the emitted event:

Vue.component('author-detail', {
  template: `
    <div>
      <h2 id="owner-name">{{ owner.name }}</h2>
      <p>{{ owner.email }}</p>
    </div>
  `,
  props: {
    owner: {
      type: Object,
      required: true
    }
  }
})</pre>
Copy after login

Note that we are using Vue's created lifecycle method to connect to the component before it is mounted and set up the event bus.

If your application is not complex, using event bus is good, but remember that as your application grows, you may want to use Vuex instead.

Use contents in nested components of Slots

In the examples we have seen so far, the components are self-closing elements. However, in order to create components that can be grouped together in a useful way, we need to be able to nest them with each other like we would with HTML elements.

If you try to use a component with an end tag and put some content inside, you will see that Vue just swallowed it. Anything between the start and end tags of a component will be replaced by the rendering output of the component itself:

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

new Vue({ el: '#app' })</pre>
Copy after login
Copy after login
Copy after login

Luckily, Vue's slots make it possible to pass arbitrary values ​​to the component. This can be anything from the parent component to the child component, from the DOM element to other data. Let's see how they work.

The script part of the

component will look like this:

<div>
  <my-counter></my-counter>
</div></pre>
Copy after login
Copy after login
Copy after login
Copy after login

Then the template will look like this:

<template>
  <div>{{ count }}</div>
</template>

<🎜></pre>
Copy after login
Copy after login
Copy after login
The content in the

<list> component will be rendered between the <slot> element labels. We can also use fallback content in case the parent component does not inject anything.

<blogpost>
  <authordetails></authordetails>
  <postdetails></postdetails>
  <comments></comments>
</blogpost></pre>
Copy after login
Copy after login
Copy after login

If there is no content from the parent component, the fallback content will be rendered.

Conclusion

This is a high-level introduction to using components in Vue. We looked at how to create components in Vue, how to communicate from parent to child components via props, and how to communicate from child to parent components over the event bus. We then end up by looking at slots, a convenient way to combine components in a useful way. I hope you find this tutorial useful.

(The FAQs part is omitted because it is too long and does not match the pseudo-original goal. Some of the FAQs content can be re-written as needed, but the original intention must be kept unchanged.)

The above is the detailed content of A Beginner's Guide to Working With Components in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles