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

Jennifer Aniston
Release: 2025-02-14 09:35:11
Original
867 people have browsed it

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>{{ 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="language-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>{{ 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>{{ 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template