Components Basics | Vue.js (2023)

Components allow us to split the UI into independent and reusable pieces, and think about each piece in isolation. It's common for an app to be organized into a tree of nested components:

Components Basics | Vue.js (1)

This is very similar to how we nest native HTML elements, but Vue implements its own component model that allow us to encapsulate custom content and logic in each component. Vue also plays nicely with native Web Components. If you are curious about the relationship between Vue Components and native Web Components, read more here.

Defining a Component #

When using a build step, we typically define each Vue component in a dedicated file using the .vue extension - known as a Single-File Component (SFC for short):


<script>export default { data() { return { count: 0 } }}</script><template> <button @click="count++">You clicked me {{ count }} times.</button></template>


<script setup>import { ref } from 'vue'const count = ref(0)</script><template> <button @click="count++">You clicked me {{ count }} times.</button></template>

When not using a build step, a Vue component can be defined as a plain JavaScript object containing Vue-specific options:


export default { data() { return { count: 0 } }, template: ` <button @click="count++"> You clicked me {{ count }} times. </button>`}


import { ref } from 'vue'export default { setup() { const count = ref(0) return { count } }, template: ` <button @click="count++"> You clicked me {{ count }} times. </button>` // or `template: '#my-template-element'`}

The template is inlined as a JavaScript string here, which Vue will compile on the fly. You can also use an ID selector pointing to an element (usually native <template> elements) - Vue will use its content as the template source.

The example above defines a single component and exports it as the default export of a .js file, but you can use named exports to export multiple components from the same file.

Using a Component #


We will be using SFC syntax for the rest of this guide - the concepts around components are the same regardless of whether you are using a build step or not. The Examples section shows component usage in both scenarios.

To use a child component, we need to import it in the parent component. Assuming we placed our counter component inside a file called ButtonCounter.vue, the component will be exposed as the file's default export:


<script>import ButtonCounter from './ButtonCounter.vue'export default { components: { ButtonCounter }}</script><template> <h1>Here is a child component!</h1> <ButtonCounter /></template>

To expose the imported component to our template, we need to register it with the components option. The component will then be available as a tag using the key it is registered under.


<script setup>import ButtonCounter from './ButtonCounter.vue'</script><template> <h1>Here is a child component!</h1> <ButtonCounter /></template>

With <script setup>, imported components are automatically made available to the template.

It's also possible to globally register a component, making it available to all components in a given app without having to import it. The pros and cons of global vs. local registration is discussed in the dedicated Component Registration section.

Components can be reused as many times as you want:


<h1>Here are many child components!</h1><ButtonCounter /><ButtonCounter /><ButtonCounter />

Try it in the Playground

(Video) Vue JS 3 Tutorial - 29 - Components

Try it in the Playground

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.

In SFCs, it's recommended to use PascalCase tag names for child components to differentiate from native HTML elements. Although native HTML tag names are case-insensitive, Vue SFC is a compiled format so we are able to use case-sensitive tag names in it. We are also able to use /> to close a tag.

If you are authoring your templates directly in a DOM (e.g. as the content of a native <template> element), the template will be subject to the browser's native HTML parsing behavior. In such cases, you will need to use kebab-case and explicit closing tags for components:


<!-- if this template is written in the DOM --><button-counter></button-counter><button-counter></button-counter><button-counter></button-counter>

See DOM template parsing caveats for more details.

Passing Props #

If we are building a blog, we will likely need a component representing a blog post. We want all the blog posts to share the same visual layout, but with different content. Such a 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. To pass a title to our blog post component, we must declare it in the list of props this component accepts, using the props optiondefineProps macro:


<!-- BlogPost.vue --><script>export default { props: ['title']}</script><template> <h4>{{ title }}</h4></template>

When a value is passed to a prop attribute, it becomes a property on that component instance. The value of that property is accessible within the template and on the component's this context, just like any other component property.


<!-- BlogPost.vue --><script setup>defineProps(['title'])</script><template> <h4>{{ title }}</h4></template>

defineProps is a compile-time macro that is only available inside <script setup> and does not need to be explicitly imported. Declared props are automatically exposed to the template. defineProps also returns an object that contains all the props passed to the component, so that we can access them in JavaScript if needed:


const props = defineProps(['title'])console.log(props.title)

See also: Typing Component Props

If you are not using <script setup>, props should be declared using the props option, and the props object will be passed to setup() as the first argument:


export default { props: ['title'], setup(props) { console.log(props.title) }}

A component can have as many props as you like and, by default, any value can be passed to any prop.

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


<BlogPost title="My journey with Vue" /><BlogPost title="Blogging with Vue" /><BlogPost title="Why Vue is so fun" />

In a typical app, however, you'll likely have an array of posts in your parent component:


export default { // ... data() { return { posts: [ { id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' } ] } }}


const posts = ref([ { id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' }])

Then want to render a component for each one, using v-for:


(Video) COMPONENTS | VueJS | Learning the Basics

<BlogPost v-for="post in posts" :key="" :title="post.title" />

Try it in the Playground

Try it in the Playground

Notice how v-bind is used to pass dynamic prop values. 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 Events #

As we develop our <BlogPost> 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 at its default size.

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


data() { return { posts: [ /* ... */ ], postFontSize: 1 }}


const posts = ref([ /* ... */])const postFontSize = ref(1)

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


<div :style="{ fontSize: postFontSize + 'em' }"> <BlogPost v-for="post in posts" :key="" :title="post.title" /></div>

Now let's add a button to the <BlogPost> component's template:


<!-- BlogPost.vue, omitting <script> --><template> <div class="blog-post"> <h4>{{ title }}</h4> <button>Enlarge text</button> </div></template>

The button doesn't do anything yet - we want clicking the button to communicate to the parent that it should enlarge the text of all posts. To solve this problem, components provide a custom events system. 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:


<BlogPost ... @enlarge-text="postFontSize += 0.1" />

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


<!-- BlogPost.vue, omitting <script> --><template> <div class="blog-post"> <h4>{{ title }}</h4> <button @click="$emit('enlarge-text')">Enlarge text</button> </div></template>

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

Try it in the Playground

Try it in the Playground

We can optionally declare emitted events using the emits optiondefineEmits macro:


<!-- BlogPost.vue --><script>export default { props: ['title'], emits: ['enlarge-text']}</script>


(Video) Vue JS 3 tutorial #6 Make First Component

<!-- BlogPost.vue --><script setup>defineProps(['title'])defineEmits(['enlarge-text'])</script>

This documents all the events that a component emits and optionally validates them. It also allows Vue to avoid implicitly applying them as native listeners to the child component's root element.

Similar to defineProps, defineEmits is only usable in <script setup> and doesn't need to be imported. It returns an emit function that is equivalent to the $emit method. It can be used to emit events in the <script setup> section of a component, where $emit isn't directly accessible:


<script setup>const emit = defineEmits(['enlarge-text'])emit('enlarge-text')</script>

See also: Typing Component Emits

If you are not using <script setup>, you can declare emitted events using the emits option. You can access the emit function as a property of the setup context (passed to setup() as the second argument):


export default { emits: ['enlarge-text'], setup(props, ctx) { ctx.emit('enlarge-text') }}

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:


<AlertBox> Something bad happened.</AlertBox>

Which might render something like:

This is an Error for Demo Purposes

Something bad happened.

This can be achieved using Vue's custom <slot> element:


<template> <div class="alert-box"> <strong>This is an Error for Demo Purposes</strong> <slot /> </div></template><style scoped>.alert-box { /* ... */}</style>

As you'll see above, we use the <slot> as a placeholder where we want the content to go – and that's it. We're done!

Try it in the Playground

Try it in the Playground

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:

Open example in the Playground

Open example in the Playground

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


<!-- Component changes when currentTab changes --><component :is="currentTab"></component>


(Video) How To Use Components In Vue JS

<!-- Component changes when currentTab changes --><component :is="tabs[currentTab]"></component>

In the example above, the value passed to :is can contain either:

  • the name string of a registered component, OR
  • the actual imported component object

You can also use the is attribute to create regular HTML elements.

When switching between multiple components with <component :is="...">, a component will be unmounted when it is switched away from. We can force the inactive components to stay "alive" with the built-in <KeepAlive> component.

DOM Template Parsing Caveats #

If you are writing your Vue templates directly in the DOM, Vue will have to retrieve the template string from the DOM. This leads to some caveats due to browsers' native HTML parsing behavior.


It should be noted that the limitations discussed below only apply if you are writing your templates directly in the DOM. They do NOT apply if you are using string templates from the following sources:

  • Single-File Components
  • Inlined template strings (e.g. template: '...')
  • <script type="text/x-template">

Case Insensitivity #

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


// camelCase in JavaScriptconst BlogPost = { props: ['postTitle'], emits: ['updatePost'], template: ` <h3>{{ postTitle }}</h3> `}


<!-- kebab-case in HTML --><blog-post post-title="hello!" @update-post="onUpdatePost"></blog-post>

Self Closing Tags #

We have been using self-closing tags for components in previous code samples:


<MyComponent />

This is because Vue's template parser respects /> as an indication to end any tag, regardless of its type.

In DOM templates, however, we must always include explicit closing tags:



This is because the HTML spec only allows a few specific elements to omit closing tags, the most common being <input> and <img>. For all other elements, if you omit the closing tag, the native HTML parser will think you never terminated the opening tag. For example, the following snippet:


<my-component /> <!-- we intend to close the tag here... --><span>hello</span>

will be parsed as:


<my-component> <span>hello</span></my-component> <!-- but the browser will close it here. -->

Element Placement Restrictions #

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:


<table> <blog-post-row></blog-post-row></table>

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


<table> <tr is="vue:blog-post-row"></tr></table>


When used on native HTML elements, the value of is must be prefixed with vue: in order to be interpreted as a Vue component. This is required to avoid confusion with native customized built-in elements.

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 - build something fun, or check out some of the Examples if you haven't already.

Once you feel comfortable with the knowledge you've just digested, move on with the guide to learn more about components in depth.


What should be a component Vue? ›

Vue components are written as a combination of JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure.

Is Vue more difficult than React? ›

React documentation is slightly harder to read, which resulted in a slow ramp-up in comparison with Vue. js, mostly based on the extra effort to learn JSX. In summary, both are quite similar in their structure, but Vue. js is slightly easier to learn as it allows HTML and JSX.

Is Vue difficult to learn? ›

Vue is lightweight, easy to learn, pleasant to write in, and not difficult to integrate with legacy technologies or an application without a specified framework. Because of its familiar templating syntax and use of components, integrating or migrating existing projects to Vue is faster and smoother.

How many days it will take to learn Vue JS? ›

Learn Vue js will take a complete beginner one to two weeks. However, a more experienced programmer might be able to learn the basic concepts within a few hours. It's recommended that people are fluent in Javascript before attempting to learn Vue js. Learning Javascript will take between six to nine months.

What are the 3 parts of a component in Vue? ›

Components are reusable Vue instances with custom HTML elements. Components can be reused as many times as you want or used in another component, making it a child component. Data, computed, watch, and methods can be used in a Vue component.

What do @component do? ›

@Component is a class-level annotation. It is used to denote a class as a Component. We can use @Component across the application to mark the beans as Spring's managed components. A component is responsible for some operations.

Does Facebook use Vue? ›

The fact that Facebook is one of many websites using Vue.

Is Vue overtaking React? ›

However, considering GitHub, Vue overtakes React with its stars. This means both the languages are quite popular and are here to stay for long.

Is Vue js good for big projects? ›

Vue is easy to understand and absorb. The learning curve is less steep and development concepts are simple to understand. It helps to develop large-scale projects. The fact is that Vue adopted the best concepts of React and Angular.

How much do Vue employees get paid? ›

Vue Entertainment Salary FAQs

The average Vue Entertainment salary ranges from approximately £25,165 per year for a Cinema Manager to £50,275 per year for a Customer Assistant. The average Vue Entertainment hourly pay ranges from approximately £6 per hour for a Cinema Worker to £8 per hour for a Customer Assistant.

Is Vue harder than Angular? ›

Learning Curve

Vue is simpler to use than Angular since it has built-in app templates and allows for more flexibility. Furthermore, it is easy to integrate Angular or React-based mobility solutions into the Vue platform as Vue. js was created by combining Angular and React.

How can I learn Vue faster? ›

First, learn the essentials of Vue 2.0 by going through the main concepts and syntax. Then, build your first single-page app with Vue. Second, create an application that handles HTTP Web Requests in Vue and uses a public API. Extend upon this application next, learning VueRouter for multi-page applications.

Is Vue growing faster than React? ›

Overall, Vue may offer higher performance speed and scale your projects. However, React. js has a better ecosystem, many templates, and extra tools. This is why teams on smaller projects often opt for Vue, because speed is a decisive factor, whereas React fits complex web platforms better.

Is Vue good for small projects? ›

It might seem pretty fresh, but Vue already has a number of great tools developed around it, and it's been proven to be suitable for projects of any size.

Is Vue beginner friendly? ›

Secondly, this framework is exceptionally easy to learn out of all the front-end frameworks for web development. Developers can easily pick the basics of Vue within a few hours of testing stuff and reading documents. It also takes efficient ideas from its rivals, such as the data binding feature.

What are the types of components? ›

Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.

What are props in Vue components? ›

What are props? In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components. When we build our applications out of components, we end up building a data structure called a tree.

Why do we use components? ›

Basically, it is an array of value for the providers which is used to provide the services which are being used by the current component. Thus, it is not a required property, so we can ignore it if we don't need it.

How do I use Vue components? ›

To create a component, following is the syntax. Vue. component('nameofthecomponent',{ // options}); Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids component_test and component_test1.

Why do components fail? ›

Component failures happen due to mechanical, thermal, environmental, thermal, electrical, packaging, and aging factors.

Does Apple use Vue? ›

Apple offers certification programs for IT professionals using OnVUE online proctoring.

Why is Vue JS so popular? ›

Vue. js is known for its flexibility as it gives an opportunity to write fast and run directly from a browser. Developers can build complex apps using bundling, routing, ES6, JSX, components, and more. Providing access to a wide range of environments, Vue is a popular choice for cross-platform app development.

What problem does Vue solve? ›

Vue, a jQuery successor

It made writing cross-browser JavaScript a lot easier, which was a big plus at the time since it dramatically decreased the need for developers to mess with various browsers' quirks and inconsistencies.

Does Facebook use Vue or React? ›

Vue. js has already earned a significant spot among the most popular JavaScript frameworks and many well-known companies use Vue. js such as Facebook, Netflix or Adobe.

Why is Vue not popular? ›

Vue js is not popular because it's a new framework compared to React js and Angular js, and it's not used by a lot of market leaders, another reason is it has very few resources compared to the popular frameworks.

Why people prefer Vue over React? ›

Vue also uses the virtual DOM, but compared to React, Vue has better performance and stability. According to this data, Vue and React's performance difference is subtle since it is only a few milliseconds. This proves that Vue and React are very similar in terms of performance.

Does Google use VueJS? ›

Even Google built their Careers platform based on VueJS and not their native Angular framework, and Apple built their tutorial website with VueJS.

Is VueJS faster than Angular? ›

Vue. js is a faster, simpler, and sleeker child of the React and Angular JS frameworks. Developed by Evan You in 2014, it has amassed a massive following in a very short time for its lightweight, progressive web development framework.

Does Vue pay monthly? ›

How often do you get paid at vue cinemas? The last working day of every month.

How long are VUE shifts? ›

Contract is 4 hours.

Do you get free tickets if you work at Vue? ›

What benefits does Vue Cinemas offer? Free tickets and 40% discount on food/drink.

Is Vue js still a thing? ›

With all the great features and benefits of using Vue. js to create frontend applications, Vue. js itself is still a client-side library that only renders and manipulates DOM elements. Server-side rendering helps client-side frameworks such as Vue.

Is Vue js better than React? ›

Vue. js combined the top-level features of React and Angular, but its main feature is the perfect user experience. Also, it leveraged the capacity of the virtual DOM and optimized the code structure.

Is Vue better than bootstrap? ›

According to the StackShare community, Bootstrap has a broader approval, being mentioned in 7044 company stacks & 1115 developers stacks; compared to Vue. js, which is listed in 849 company stacks and 1219 developer stacks.

Is Vue full stack? ›

js, Vue, and Node. js) is a popular NEW stack for building full-stack web applications. It allows developers to write an entire application—front-end, back-end, and database—using only JavaScript.

Are Vue developers in demand? ›

Many organizations are looking to hire Vue. js developers for their projects. However, since it takes software developers a while to master this framework, the demand for Vue. js experts is unquestionably high.

Why is Vue js so popular in China? ›

He is also supportive of the community. That might be one of the reasons why Vue. js is popular in China – that's because local developers are aware of the framework, some of them might know who is the creator of it, so eventually, it leads to the wider usage of the framework.

Does Netflix use React? ›

Netflix uses ModeJs with the assistance of React for image synthesis. In this article, we have also incorporated a React Netflix clone project with source code which is also available on Netflix clone react js Github. This article will also help you in checking out the Netflix clone project report.

Which has more jobs React or Vue? ›

Popularity and Job Market

Vue has a lesser community, having limited resources and modules, but it is still supported by Evan You and the team. React is well ahead of Vue in terms of job opportunities, having been around since 2013 and been championed by the social media behemoth Facebook.

Why is Vue slower than React? ›

The default size of React is about 100 Kb, Vue. js is around 80 Kb. This might not seem like the most important factor at first, but the heavier the JS code is, the slower the end app performance will be.

Does VueJS make money? ›

Vue's creation is funded through Evan's Patreon account, which now pulls in over $16,000/mo, enough to cover his salary along with his new hire—a developer dedicated to triaging issues.

What IDE should I use for Vue? ›

IDE Support

The recommended IDE setup is VSCode + the Volar extension. Volar provides syntax highlighting, TypeScript support, and intellisense for template expressions and component props. Volar replaces Vetur, our previous official VSCode extension for Vue 2.

Do kids pay at Vue? ›

Both adults and children pay from £2.49/€2.99 per ticket. Mini Mornings are run every Saturday and Sunday morning from 10am, plus every day in the school holidays (with availability likely to change depending on when your child's holidays occur).

Can you drink alcohol at Vue? ›

No there is not. However alcoholic drinks are available to purchase at the concessions counter.

Can I take coffee into Vue? ›

Cineworld replied: "Hey Bünyamin, as long as it's not hot or strong smelling food, you're perfectly fine to bring it with you." Vue gave a similar response, writing: "You sure are! You're welcome to bring your own cold food and non-alcoholic drinks into any of our venues. I hope this helps."

Why must component data be a function Vue? ›

why Vue forces the data property to be a function is that each instance of a component should have its own data object. If we don't do that, all instances will be sharing the same object and every time we change something, it will be reflected in all instances.

Should I use Vue class component? ›

This is the main advantage of using the Vue Class Component library, you transform your components into classes, which allows you to better organize your code, and more. With it you can create custom Decorators, extend other components and/or mixins and use additional Hooks when using Vue Router.

What are the values of components? ›

Component Value means underlying factors that are part of the cost of providing services that are built into the waiver rates methodology to calculate service rates. Component Value means for any Investment and Other Investment Position, the Value of such Investment or Other Investment Position.

What should be a component in angular? ›

A component is a directive with a template that allows building blocks of a UI in an Angular application. Components will always have a template, a selector, and may or may not have a separate style.

Do all components have state within it in Vue JS? ›

Components Can Still Have Local State

Using Vuex doesn't mean you should put all the state in Vuex. Although putting more state into Vuex makes your state mutations more explicit and debuggable, sometimes it could also make the code more verbose and indirect.

How do I pass data from one component to another component in Vue? ›

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!

Are class components outdated? ›

Yes, React class components will fade away in the future. If you want to embrace modern React, then you should use function components with hooks. That's why you will find most tutorials out there teaching modern React and no class components anymore.

Are class based components dead? ›

Class components are not dead.


1. Vue js tutorial in Hindi #4 Make component
(Code Step By Step)
2. Transfer Data Between Components In Vue JS
3. Vue JS 3 Tutorial #5 - Multiple Components
(Evan Does Tech)
4. Vue JS 2 Tutorial #15 - Intro to Components
(The Net Ninja)
5. Learn Vue.js Functional Components In 10 Minutes
(Program With Erik)
6. Vue.js Tutorial From Scratch - e06 - Components 101
(Coder's Tape)
Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated: 01/04/2023

Views: 6053

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.