Components are individual blocks that contain UI logic that can be reused in a Vue application.
They make it easy to organize and maintain code while building large and complex applications.
In this article, we will look at how to declare and use Vue components with examples.
Declaring Vue Component
Let us begin by creating a new application using the Vue CLI.
vue create my-component
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
$ cd my-component
$ npm run serve
The application by default will run on port 8080.
We will delete the default HelloWorld.vue
file and also remove its reference from the App.vue
file.
// App.vue
<template>
<h1>Vue Js</h1>
</template>
<script>
export default {
}
</script>
We usually define a component in a seperate file which has a .vue
extension know as single-file-component.
Let’s create a file called ProductList.vue
inside the components folder. This file will contain all the UI logic to display the products.
touch src/components/ProductList.vue
// ProductList.vue
<template>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - {{ product.price }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
products: [
{
id: 1,
name: 'Jeans',
price: '$20'
},
{
id: 2,
name: 'T-shirt',
price: '$10'
},
{
id: 3,
name: 'Hoodie',
price: '$30'
}
]
}
}
}
</script>
In this case, we have defined a products
property which is an array of product objects. Each product contains id
, name
, and price
.
data() {
return {
products: [
{
id: 1,
name: 'Jeans',
price: '$20'
},
{
id: 2,
name: 'T-shirt',
price: '$10'
},
{
id: 3,
name: 'Hoodie',
price: '$30'
}
]
}
}
In the template, we loop through all the products
using v-for
and display the products using a list.
<template>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - {{ product.price }}
</li>
</ul>
</template>
Let’s import this file in our App.vue
file.
import ProductList from "./components/ProductList.vue";
To use this component in App.vue
we will add the following code:
export default {
components: {
ProductList
}
This tells Vue that we want to use the ProductList
component in App.vue
's template.
Now we can use this component using tag <product-list>
in our App.vue
template.
// App.vue
<template>
<h1>Vue Js</h1>
<product-list></product-list>
</template>
So the entire App.vue
file should look something like this:
<template>
<h1>Vue Js</h1>
<product-list></product-list>
</template>
<script>
import ProductList from "./components/ProductList.vue"
export default {
components: {
ProductList
}
}
</script>
Once you run the server and load the page. It should look this the below screenshot.
All the content from the ProductList.vue
component will now get used in the App.vue
.