Vue component here, Vue components there. Components everywhere!

Marcin Kwiatkowski /
Vue component here, Vue components there. Components everywhere!

Previously I showed you how to get started with Vue, and I have promised that there will be a second part, and here you go!

Spoiler alert: there will be even a third series but to the point!

So since we know the basics of Vue, now we have to dig into the Vue platform to create a custom component. We first create a component representing every player in our football (soccer??) team. We learn several basic concepts throughout the process, like calling components within another component, sending the data to the component via props, or using a provide/inject approach.

Components Basics

Components are reusable Vue instances. In the App that I started work on in the last article, there is the main component: App.vue.

Any other components accept the same properties as the root component: data, computed, methods, watch, etc.

vue components are reusable vue instances

Three parts of a component in Vue

Single-file component vue file comprises three pieces: HTML syntax to determine the visual view for the component. JavaScript provides a list of properties for creating the component, using standard JavaScript module syntax exports in JS. Style sheets are used in defining the best user interfaces.

You have to make a new file (typically in the components folder). Let's name this file: PlayerCard.vue.

First, add a template section with HTML elements:

1<template>
2    <h1>This is a new component</h1>
3</template>
4

Export Vue components

To be honest, for a long time, I thought that I needed to add another section beneath the Templates section: <script></script> and add an export object, like this:

1<script>
2export default {}
3</script>
4

but it is not necessary. You can have components only with the template section. Anyway, typically, you have more sophisticated components in apps, so it's good to add an export default object with a name property.

1<template>
2    <h1>This is a new component</h1>
3</template>
4<script>
5export default {
6    name: 'PlayerdCard'
7}
8</script>
9

How to import Vue components

Since we have exported components, we can use them in another place. In this case, we are going to import the PlayerdCard Vue component into the App component. To do so, let's:

Import child components into parent components inside script tags

1<script>
2import PlayerCard from './components/PlayerCard.vue';
3
4export default {
5  name: 'App',
6(...)
7

Register child component in a parent component

We need to let the App component know that it can use the PlayerdCard component. There is a components property that is responsible for registering components:

1<script>
2import PlayerCard from './components/PlayerCard.vue';
3
4
5export default {
6  name: 'App',
7  components: { PlayerCard },
8(...)
9

FINALLY. Use child component to render a child component template.

To render the PlayerCard component, you must put a custom element inside the App component template. We imported the component as PlayerCard, so this is the name of the custom element:

1<template>
2  <PlayerCard/>
3</template>
4
5<script>
6import PlayerCard from './components/PlayerCard.vue';
7
8export default {
9  name: 'App',
10  components: { PlayerCard },
11  // other stuff below
12  data() {
13    return {
14      players: [
15      ]
16    }
17  },
18  computed: {
19  },
20  methods: {
21  watch: {
22  }
23}
24</script>
25<style>
26</style>
27

Global and local components

We registered globally our first component in App.vue, a root component. This is a typical approach, but sometimes you have specific components used in a minor part of the App.

Vue allows you to register components in other components. So you can register the component in the PlayerCard component instance, and you can use it and in any children of it then.

It means that the component is registered locally, and it will not be available in parent components - in our case, in the app component object.

Component communication

The PlayerdCard component is working, but it's not too helpful. Let's add some content to it:

1<template>
2    <div class="player">
3        <h1>{{ player.name }}</h1>
4        <img :src="player.image" :alt="player.name" />
5        <p><strong>{{ player.club }}, {{ player.country }}</strong></p>
6        <p>Position: {{ player.position }}</p>
7        <p>
8            Price: {{ player.price }}
9            <strong v-if="player.playerLabel">{{ player.playerLabel }}</strong>
10        </p>
11        <button type="button" @click="toggleForSale()">
12            <span v-if="player.forSale">Remove from transfer list</span>
13            <span v-if="!player.forSale">Add to transfer list</span>
14        </button>
15    </div>
16</template>
17

A player object is used in many places, but the component object does not include player data. How to pass player data to the component?

Introducing props

To pass data to the components, you can use props. Props are HTML attributes that can be, let's say, moved to the component scope.

First, we need to define that the PlayerCard component can receive a player prop:

1// PlayerCard.vue
2export default {
3    name: 'PlayerdCard',
4    props: ['player']
5}
6

Then we can pass the player prop to the PlayerCard in App.vue

1<template>
2  <PlayerCard :player="players[0]"/>
3</template>
4

a player is an array defined in data of the App component:

1export default {
2  name: 'App',
3  components: { PlayerCard },
4  data() {
5    return {
6      players: [
7        {
8          id: 1,
9          name: 'Mo Salah',
10          club: 'Liverpool FC',
11          country: 'Egypt',
12          position: 'Striker',
13          price: 2000,
14          image: './avatar.png',
15          forSale: false 
16        },
17        {
18          id: 2,
19          name: 'Robert Lewandowski',
20          club: 'FC Bayern',
21          country: 'Poland',
22          position: 'Striker',
23          price: 3000,
24          image: './avatar.png',
25          forSale: true 
26        }
27      ]
28    }
29  }
30}
31</script>
32

To make the example more accurate, let's iterate through the players' array using v for directive and display all players on the screen:

1<template>
2  <PlayerCard v-for="player in players" :key="player.id" :player="player"/>
3</template>
4

Supported props

Above we passed an object as a prop, but you can also give other types. Take a look at prop types that Vue supports:

  • String

  • Number

  • Boolean

  • Array

  • Object

  • Date

  • Function

  • Symbol

Props validation

When I registered a prop in the PlayerCard component, I just pasted a name into the props array:

1props: ['player']
2

but there is an option to validate props. Take a look:

1props: {
2    player: Object
3}
4

Now, the component expects that player will be an object, so any other type passed to the component will throw a warning in the console.

Also, you can specify that prop is required:

1props: {
2    player: Object,
3    required: true
4}
5

Default value:

1props: {
2    player: Object,
3    default: {
4        name: 'Bot'
5   }
6}
7

Besides, there are more options. Please follow Vue docs to meet them all. The last thing that I want to do here is repeat Vue docs.

After this step, the App renders two players:

The PlayerCard vue component in action

Custom events: child-parent communication

Our very first Vue component works, but there are some bugs. When I click on "add to transfer list," I see the error in the console:

1Uncaught TypeError: _ctx.toggleForSale is not a function
2

That happens because, in the PlayerCard, we don't have the toggleForSale function. That function is in the scope of the App Vue component.:

1methods: {
2  toggleForSale() {
3    this.forSale = !this.forSale;
4  }
5},
6

Anyway, that function is outdated. It worked in the case when we had one player. Now we have an array of players, so we have to update the toggleForSale function to make that possible.

1methods: {
2  toggleForSale(playerId) {
3    const player = this.players.find(player => player.id === playerId);
4    player.forSale = !player.forSale;
5  }
6},
7

Now the function receives the playerId parameter to identify which player should be modified, but still – the toggleForSale function is in the scope of the App component. Is it possible to call this method from other Vue components? Especially from child components?

There is a way to do that: custom events!

vue app js component can communicate with other vue instance

Defining custom events

To define an event, you should add it to the emits array like this:

1export default {
2    name: 'PlayerdCard',
3    props: ['player'],
4    emits: ['toggle-for-sale']
5}
6

Technically, it's not obligatory but is a good practice to define events because then it's more clear to understand how components work.

The next step is emitting our custom event when the user clicks on the button:

1<button type="button" @click="$emit('toggle-for-sale', player.id)">
2    <span v-if="player.forSale">Remove from transfer list</span>
3    <span v-if="!player.forSale">Add to transfer list</span>
4</button>
5

Lastly, we have to listen to this event in the App component:

1// App.vue
2<template>
3  <PlayerCard 
4    v-for="player in players" 
5    :key="player.id" 
6    :player="player"
7    @toggle-for-sale="toggleForSale"
8  />
9</template>
10

For the @toggle-for-sale custom event, I bound toggleForSale function available in App.js, and now the functionality works as expected.

Validating custom events

As props, the custom events can be validated. It's possible by defining emits not as an array but as objects. Each property of that object is a custom event name, and it's a validation function:

1emits: {
2    'toggle-for-sale': (playerId) => {
3        if (!playerId) {
4            console.warn('Player ID is missing')
5
6            return false;
7        }
8
9        return true
10    }
11}
12

Prop drilling problem

If you came here from React, you are probably familiar with a common problem called: props drilling. If not, let me explain quickly by example.

We are going to add two components to the PlayerCard component:

  • PlayerData

  • PlayerAttributes

before we start implementing those components, we add some additional data to our players:

1players: [
2  {
3    id: 1,
4    name: 'Mo Salah',
5    club: 'Liverpool FC',
6    country: 'Egypt',
7    position: 'Striker',
8    price: 2000,
9    image: './avatar.png',
10    forSale: false,
11    birthday: '10/10/2000',
12    growth: '180cm',
13    betterLeg: 'right',
14    speed: 94,
15    shooting: 90,
16    passes: 89,
17    dribble: 99,
18    defense: 30,
19    physical: 85
20  },
21  {
22    id: 2,
23    name: 'Robert Lewandowski',
24    club: 'FC Bayern',
25    country: 'Poland',
26    position: 'Striker',
27    price: 3000,
28    image: './avatar.png',
29    forSale: false,
30    birthday: '20/05/2000',
31    growth: '190cm',
32    betterLeg: 'right',
33    speed: 90,
34    shooting: 99,
35    passes: 89,
36    dribble: 85,
37    defense: 78,
38    physical: 89
39  }
40]
41

The PlayerData component

1// PlayerCard/PlayerData.vue
2
3<template>
4    <div class="player-data">
5        <ul>
6            <li>
7                <strong>Birthday: </strong>
8                <span>{{ player.birthday }}</span>
9            </li>
10            
11            <li>
12                <strong>Growth: </strong>
13                <span>{{ player.growth }}</span>
14            </li>
15
16
17            <li>
18                <strong>Better leg: </strong>
19                <span>{{ player.betterLeg }}</span>
20            </li>
21        </ul>
22    </div>
23</template>
24<script>
25export default {
26    name: 'PlayerData',
27    props: ['player'],
28}
29</script>
30

This component renders some information about a player like a birthday, growth, and better leg.

Let's import it and register in the playerCard Vue component:

1<script>
2import PlayerData from './PlayerCard/PlayerData.vue'
3
4export default {
5    name: 'PlayerdCard',
6    props: ['player'],
7    emits: ['toggle-for-sale'],
8    components: {
9        PlayerData
10    }
11}
12</script>
13

Now we can use it in the template section:

1// PlayerCard.vue
2
3<template>
4    <div class="player">
5        (...)
6
7        <div class="additional-data">
8            <PlayerData :player="player"/>
9        </div>
10    </div>
11</template>
12

The PlayerAttributes component

This component will be pretty the same. The difference is that it renders other data:

1<template>
2    <div class="player-attributes">
3        <ul>
4            <li>
5                <strong>Speed: </strong>
6                <span>{{ player.speed }}</span>
7            </li>
8            
9            <li>
10                <strong>Shooting: </strong>
11                <span>{{ player.shooting }}</span>
12            </li>
13
14
15            <li>
16                <strong>Passes: </strong>
17                <span>{{ player.passes }}</span>
18            </li>
19
20
21            <li>
22                <strong>Dribble: </strong>
23                <span>{{ player.passes }}</span>
24            </li>
25
26
27            <li>
28                <strong>Passes: </strong>
29                <span>{{ player.dribble }}</span>
30            </li>
31
32
33            <li>
34                <strong>Defense: </strong>
35                <span>{{ player.defense }}</span>
36            </li>
37
38
39            <li>
40                <strong>Physical: </strong>
41                <span>{{ player.physical }}</span>
42            </li>
43        </ul>
44    </div>
45</template>
46<script>
47export default {
48    name: 'PlayerData',
49    props: ['player'],
50}
51</script>
52

Note: for now, those components looks the same, but in the future, I am going to add more logic there, so don't worry, I have an idea πŸ˜†

The last thing in this step is registering, importing, and using the new component in PlayerCard.

The final code of the PlayerCard component:

1<template>
2    <div class="player">
3        <h1>{{ player.name }}</h1>
4        <img :src="player.image" :alt="player.name" />
5        <p><strong>{{ player.club }}, {{ player.country }}</strong></p>
6        <p>Position: {{ player.position }}</p>
7        <p>
8            Price: {{ player.price }}
9            <strong v-if="player.playerLabel">{{ player.playerLabel }}</strong>
10        </p>
11        <button type="button" 
12            @click="$emit('toggle-for-sale', player.id)">
13            <span v-if="player.forSale">Remove from transfer list</span>
14            <span v-if="!player.forSale">Add to transfer list</span>
15        </button>
16
17        <div class="additional-data">
18            <PlayerData :player="player"/>
19            <PlayerAttributes :player="player"/>
20        </div>
21    </div>
22</template>
23<script>
24import PlayerData from './PlayerCard/PlayerData.vue';
25import PlayerAttributes from './PlayerCard/PlayerAttributes.vue';
26
27export default {
28    name: 'PlayerdCard',
29    props: ['player'],
30    emits: ['toggle-for-sale'],
31    components: {
32        PlayerData,
33        PlayerAttributes
34    }
35}
36</script>
37

This is rendered playerCard in the browser:

Vue Single File Component rendered

I wanted to show you a props drilling problem if you forgot, and here you go. We have the PlayerdCard component that receives the player as a prop, and that component has children: PlayerData and PlayerAttributes components that also receive the player as a prop.

Moreover, PlayerCard's child components also can have children that need a player. A prop drilling problem is about passing props from parent to child. It can be problematic and frustrating if you have a big tree of components.

In React application, there is a way to handle that differently – by using Context. In vue, there is something familiar.

provide/inject as a solution

Instead of passing props to every child component, you can provide data in the parent component and inject this data into children. Take a look:

1export default {
2  name: 'App',
3  components: { PlayerCard },
4  data() {
5    return {
6      players: [
7        {
8          id: 1,
9          name: 'Mo Salah',
10          club: 'Liverpool FC',
11          country: 'Egypt',
12          position: 'Striker',
13          price: 2000,
14          image: './avatar.png',
15          forSale: false,
16          birthday: '10/10/2000',
17          growth: '180',
18          betterLeg: 'right',
19          speed: 94,
20          shooting: 90,
21          passes: 89,
22          dribble: 99,
23          defense: 30,
24          physical: 85
25        },
26        {
27          id: 2,
28          name: 'Robert Lewandowski',
29          club: 'FC Bayern',
30          country: 'Poland',
31          position: 'Striker',
32          price: 3000,
33          image: './avatar.png',
34          forSale: false,
35          birthday: '20/05/2000',
36          growth: '190',
37          betterLeg: 'right',
38          speed: 90,
39          shooting: 99,
40          passes: 89,
41          dribble: 85,
42          defense: 78,
43          physical: 89
44        }
45      ]
46    }
47  },
48  provide: {
49    players: this.players
50  },
51}
52

Then in any child, you can inject players:

1export default {
2    name: 'PlayerData',
3    inject: ['player'],
4}
5

Once I injected player into the PlayerData and PlayerAttributes component, I can remove the player prop from them in the PlayerCard component:

1<div class="additional-data">
2    <PlayerData />
3    <PlayerAttributes/>
4</div>
5

The App still works, but data is passed differently.

Dynamic components

Last thing that I want to show you are dynamic components. Now we have two components in the PlayerCard component: PlayerData and PlayerAttributes, and they are rendered on the screen. I would like to have something like tabs and the possibility to change the active tab. Then only one component corresponding to chosen tab will be visible.

First, create a nav for tabs:

1// PlayerCard.js
2<nav>
3    <button type="button" @click="selectTab('PlayerData')">Player Data</button>
4    <button type="button" @click="selectTab('PlayerAttributes')">Player Attributes</button>
5</nav>
6

I bound the selectTab method to click event so let's create this method:

1methods: {
2    selectTab(tab) {
3        this.selectedTab = tab;
4    } 
5},
6

Besides, add a new data property with the selectedTab field:

1data() {
2    return {
3        selectedTab: 'PlayerData'
4    }
5},
6

Lastly, let's render our components dynamically by adding a <component> vue particular component and binding selectedTab property to is prop on that component like this:

1<div class="additional-data">
2    <component :is="selectedTab"/>
3</div>
4

Thanks to that, we can render dynamic components based on data property like this example. When a property is changed, Vue dynamically switch component and render them.

Complete code including dynamic components:

1<template>
2    <div class="player">
3        <h1>{{ player.name }}</h1>
4        <img :src="player.image" :alt="player.name" />
5        <p><strong>{{ player.club }}, {{ player.country }}</strong></p>
6        <p>Position: {{ player.position }}</p>
7        <p>
8            Price: {{ player.price }}
9            <strong v-if="player.playerLabel">{{ player.playerLabel }}</strong>
10        </p>
11        <button type="button" 
12            @click="$emit('toggle-for-sale', player.id)">
13            <span v-if="player.forSale">Remove from transfer list</span>
14            <span v-if="!player.forSale">Add to transfer list</span>
15        </button>
16
17
18        <nav>
19            <button type="button" @click="selectTab('PlayerData')">Player Data</button>
20            <button type="button" @click="selectTab('PlayerAttributes')">Player Attributes</button>
21        </nav>
22
23
24<div class="additional-data">
25    <component :is="selectedTab"/>
26</div>
27    </div>
28</template>
29<script>
30import PlayerData from './PlayerCard/PlayerData.vue';
31import PlayerAttributes from './PlayerCard/PlayerAttributes.vue';
32
33
34export default {
35    name: 'PlayerdCard',
36    props: ['player'],
37    emits: ['toggle-for-sale'],
38    provide() {
39        return {
40            player: this.player
41        }
42    },
43    components: {
44        PlayerData,
45        PlayerAttributes
46    },
47    data() {
48        return {
49            selectedTab: 'PlayerData'
50        }
51    },
52    methods: {
53        selectTab(tab) {
54            this.selectedTab = tab;
55        } 
56    }
57}
58</script>
59

The App looks like this for now:

dynamic components in action

It isn't lovely:😎 but, don't worry – next time, I will show you how to style Vue applications.

Summary

This Vue is a Javascript framework for building web apps. As with other frameworks, it allows using reusable components. Thanks to that, frontend development and building single-page applications are easy and efficient.

Today I showed you basics about components:

  • how to create and register vue component

  • how components communicate with other components

  • how to use props

  • what is a prop drilling problem

  • how to use provide/inject mechanism

  • how to use dynamic components

  • and so on

Share this article with your friends!

Each share supports and motivates me to create new content. Thank you!

About the author

Marcin Kwiatkowski

Frontend developer, Certified Magento Full Stack Developer, writer, based in Poland. He has eight years of professional Software engineering experience. Privately, husband and father. He likes reading books, drawing, and walking through mountains.

Read more