close menu

Introduction to Vue components

Cameron Waltz1 month

Vue is one of the big three JavaScript frontend frameworks, the other two being React and Angular. In contrast to these two, it is fully open-source, which is a benefit that many hold dear to heart.

In this article, we will look at how one of the essential parts of Vue – components – work. We will help you create two example components: a counter and a user list. This article is suited for anyone that is learning Vue or wants to see how it differs from React or Angular. 

What is a component in Vue?

Components are reusable blocks of code which help developers to create a more modular codebase. In a sense, they are the Lego blocks we use to build our app.

For example, you can easily imagine having components for an item such as a form, a menu, or an email subscription block.

You can also have components inside components, and further – it’s turtles all the way down. In fact, a Vue app is basically a tree of nested components. 

One of the ways we could subdivide instagram.com log in page into components.

In Vue projects, the components reside in the src/components folder.

What’s inside a component?

If you look at the basic boilerplate code of a component, you will see this:

<template>
  
</template>
 
<script>
export default {
 
}
</script>
 
<style>
 
</style>

There are three parts to a component: template, script, and stylesheet. 

  • Template. Vue has an HTML-based template syntax for creating the bulk of your component’s structure. It isn’t that different from regular HTML. The only difference is that it contains a few extra calls for interpolations, event handling, and other things. 
  • Script. This section contains the JavaScript necessary for the component. It has things like the name of the component, its child components, and any data and/or functions it requires. 
  • Stylesheet. This contains the CSS that you need for the component.

Build a counter component

First off, let’s try to build a counter component that will display a count and have “increase” and “decrease” buttons.

Make a new project

If you don’t have Vue, you will need to run npm install vue to get started. 

You will also need to create a new project. This one is also quite easy, just run vue create components to create a new project called components. 
Now, when we move to the directory and run the project with npm run serve, we should successfully see the Hello World! screen.

Create a counter component

Let’s start building our first component!

Go to src/components and create a new component called counter.vue. If you have Vetur installed on VSCode, you can type in vue and autocomplete for boilerplate. Otherwise, just paste in this: 

<template>
  
</template>
 
<script>
export default {
 
}
</script>
 
<style>
 
</style>

Our counter will need to display a number and have two buttons for increasing and decreasing it. 

First off, we will need to store a count variable somewhere. We will do it in the object that we export, inside data.

<script>
export default {
  data: () => ({
          count: 0
   
  })
}
</script>

We need to do this instead of data: {count: 0} so that different instances of counter wouldn’t use the same data. 

Afterwards, let’s create a methods: {} object in the same object, which will contain methods to increase & decrease the counter.

 methods: {
    increaseCounter() {
      this.count++ 
    },
 
    decreaseCounter() {
      this.count--
    }    
  }

Of course, we also need our counter to be displayed somehow. So let’s add it to the template.

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increaseCounter">Increase</button> 
    <button @click="decreaseCounter">Decrease</button> 
  </div>
</template>

Here, we use two things: 

  • {{ }} (also called moustache operator) to interpolate variables inside text.
  • @click (v-on:click) for event handling.  

This is the full counter code: 

<template>
  <div>
    <p>{{ count }}</p>
    <button v-on:click="increaseCounter">Increase</button> 
    <button v-on:click="decreaseCounter">Decrease</button> 
  </div>
</template>
 
<script>
export default {
  data: () => ({
    
      count: 0
   
  }),
 
  methods: {
    increaseCounter() {
      this.count++ 
    },
 
    decreaseCounter() {
      this.count-- 
    }    
  }
 
}
</script>
 
<style>
 
</style>

Add the counter to the app

Now, we need to add the component to the app. Go to App.vue and add this to the top of the script section.

import Counter from '@/components/counter.vue'

Then, add Counter to the template and clean out the Hello World! stuff. The file should look like this:

<template>
  <Counter/>
</template>
 
<script>
import Counter from '@/components/counter.vue'
 
export default {
  name: 'App',
  components: {
    Counter
  }
}
</script>
 
<style>
</style>

Now, if we open our app, you should see a counter: 

Build a user list component

Let’s say we want to build a component for showing a list of users. This one will be a little bit more difficult, but overall, it shouldn’t be that hard. 😉

First off, you should repeat the same actions as we did when making a counter: 

  • Create a new component called users.vue in src/components. 
  • Add the boilerplate.

Adding Axios

To display users, we will need some kind of user list. We’ll use the JSONPlaceholder API to mimic an API that would provide us with one. To fetch it, we will use Axios, a library for making requests. If you don’t already have it installed, run npm install axios. 

In the user component, go to the script section and add an import statement for Axios.

import axios from 'axios' 

Fetching the user list

To fetch the user list, we will need to do two things. 

First, we need to create an empty list of users in data for us to populate. 

  data: () => ({
    
      users: []
    
  }),

After that, we need to create a hook that will run when the component gets mounted (injected into the webpage).

We will use mounted for this. 

  mounted () {
    axios
      .get('https://jsonplaceholder.typicode.com/users')
      .then((result) => {
      this.users = result.data
      })
  }

So far, your script section should look like this:

<script>
import axios from 'axios' 
 
export default {
 
  data:() => ({
    
      users: []
    
  }),
 
  mounted () {
    axios
      .get('https://jsonplaceholder.typicode.com/users')
      .then(response) => {
      this.users = response.data
      })
  }
}
</script>

Creating a component

After that, we need to display some of our data on the screen. 

<template>
<div>
  <h2>Users</h2>
  <ul v-for="user in users":key="user.id">
    <li>{{user.name}}, contact at: {{user.email}}</li>
  </ul>
</div>
</template>

The most important part is the v-for statement. It iterates over the users list provided, making an element for each of the elements inside the object. As with the counter, we interpolate some of the variables from data as text. 

Adding the users component to the app 

This is done the same way we did it with the counter component. 

We import the users component in App.vue:

import Users from '@/components/users.vue'

List it as a component:

export default {
  name: 'App',
  components: {
    Counter,
    Users 
  }
}

And add it to the template: 

<template>
<div>
  <Users/>
  <hr>
  <Counter/>
</div>
</template>

One thing that you need to be vary about: Vue apps can only have one root element. So if you include multiple elements, you will need to wrap everything around with a div tag to not get an error. 

This is what the end result of the tutorial should look like:

We hope you had fun trying out Vue. If you want to learn more about the framework, keep reading our blog and definitely check out their awesome official guide.

Delivered by Vasterra