female developer wearing a yellow hoodie looking at a recipe website

Vue | Components & Props

We can think of components as blocks of code which we can use in different parts of our websites – again and again. They help us display code in a much neater way and are great if you need to split a massive site into smaller chunks.

Components will live within their own folder inside of your project repository. That folder will be called ‘components’. Within it, you could separate them even further and have additional sub-folders called ‘buttons’ or ‘forms’ for example. It keeps it much cleaner and easier to find things you need.

Let’s have a look at how do we register a component, what does inside of a component look like and try to answer what on 🌎 are props 😀

What do components look like and how do I use them?

Our component has to have a name, therefore the first thing we need to do is name it. Let’s say we called ours ‘PurpleParagraph’ and saved it all as PurpleParagraph.vue file.

Within it we will make a set of <template> tags, inside of which we will continue to write our HTML code.

Underneath <template> tags, we will add <scripts> where we’ll add all our methods, data, props and other ‘logic related’ stuff.

At the very bottom of the file, we could add a <style> or a <style scoped> tag if we really wanted to. Styling set here will only apply to this component and not the whole file this component ends up being a part of.

And that is how it all looks like when you write it down:

<!-- Inside of PurpleParagraph.vue file -->
<template>  
   // your HTML goes here
   <h1> {{message}} </h1>
</template>

<script>

export default {
//we set the name of our component here:
name: PurpleParagraph,

//we 'save' our data like this:
data() {
  return {
    message: 
    'This is where we continue with our HTML code',
    }
 },

// we can even add other components to this one
components: {...},

// we can add our functions here
methods: {....}

</script>

// finally, we add styling for 'message' we're displaying

<style scoped>
  h1 {
   // make text colour purple
   color: #9400D3; 
 }
</style>

So let’s break this down 🥳

We’ve added HTML within our <template> tags, in <scripts> we’ve ‘registered’ the name of our component and set a title within the ‘message’ object. Later, we added <style> tags with a ‘scoped’ next to it, which will colour our title to purple colour.

Important to notice:

1. You can only have one <template> tag per component.
2. You have to ‘register’ a name of your component before you use it.
3. If you select ‘scoped’ for styling, CSS will only apply to elements of the current component.

So to recap: import it, register it, then use it! If you skip any of those three steps you might see a set of errors in your terminal 😜

Question Time: What would be better?

1. To have 500 different component files within your component folder
2. To have few components that hold 500 lines of code each

Let me know your thoughts down in the comment section 😜

What does it look like to have multiple components inside of one page?

We can reuse the same component as many times as we want or we can mix it up and add some other ones to it too. If we imported them all and registered them all – then we just have to list them where we want to use them.

How to import components into another one?

To import our PrupleParagraph component we need to know where to use it first. So let’s imagine we’re using it directly within your App.vue file:

// inside of your App.vue file

<template>
<div class="main-section">
   <purple-paragraph> </purple-paragraph>
   <purple-paragraph> </purple-paragraph>
   <purple-paragraph> </purple-paragraph>
   <other-component>  </other-component>
</div>
</template>


<script>
// first we need to import our component to App.vue file
import PurpleParagraph from './ExampleSite/PurpleParagraph.vue'

...

// then we need to 'add' it to the list of components App.vue uses
 components: {
    OtherComponent
    PurpleParagraph,
  }

....

<script>

You can see our PurpleParagraph now became <purple-paragraph>, and you might be asking yourself why and/or how?

It’s basically automatic. Vue knows what component we’re talking about since we’ve given it a name, but it doesn’t necessarily care how we decide to spell it out. To a degree. Our HTML buddy here likes ‘kebab-case’. It’s easy to read and it’s standard practice for custom elements. Therefore, Vue will kindly let us use our component names written in kebab case.

If you wanted to keep it as <PurpleParagraph> </PurpleParagraph> you could, and it will work – it will just be, well tiring for your eyes 😅

Is that all there is to components?

Sadly, nu 😅 It’s just not that simple but this is how it all works in a nutshell. Soon enough you’ll end up writing your own features and adding/removing components how you like.

You could leave it here- but why would you? We can do this 🥳 Let’s see what are props and will they make our life difficult 😅

What are props and how can we use them to enhance our components?

Sometimes we will need to pass some data from one component to another. We’ll maybe need a method or some text, to keep it simple. This is where props come in.

Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.

We can add as many props as we want and to do that we’ll need to register them first so let’s have a look at that by going back to our component files.

// inside of your component file (PurpleParagraph.vue)
<script>
 ...

props: ['message', 'title']

 ...
</script>

Passing static values with props

We just needed to wrap our message and title into a warm pair of quotation marks of your choice. Now we’ll be able to add ‘message’ or ‘title’ to our HTML block (our component) like we would use ‘value’ or ‘colour’ and pass what we wanted in.

<!-- Inside of App.vue file -->
<div class="main-section">
   <purple-paragraph 
      title="Title of the first paragraph"
      message="This is a message we wanted to display"> 
   </purple-paragraph>

  <other-component>
  </other-component>
</div>

Here you see we used both title and message props as we would any other HTML attribute. We added equal sign and set the text within them. If we ran this we’d see this printed on our screen:

  1. Title of first paragraph.
  2. This is a message we wanted to display

So we passed our text to PurpleParagraph, why didn’t we do it with OtherComponent? Because we never registered it within OtherComponent.vue file 😅

Props can do much more than this though! 😀

Can we set a specific type of value to props?

The answer is yes. Sometimes we need to define specific types of values. Should we quickly remind ourselves what ‘types’ there are?

Strings, Numbers, Booleans, Arrays, Objects, Functions and our favourite villain – Undefined.

When written down, our props wouldn’t just look like any other array anymore. They become this:

props: {
  // Required string
    title: {
      type: String,
      required: true
    },

    // Number with a default value
    numberPropName: {
      type: Number,
      default: 100
    },

  // Object with a default value
    objectPropName: {
      type: Object,
      default: function() {
        return { message: 'hello' }
      }
    },
}

Passing dynamic values with props and v-bind

So far we’ve been passing static values around. Meaning we’ve hardcoded the text somewhere and it will always stay there, but what happens if we want our text for ‘message’ to change? We’d need to do it dynamically and v-bind can help us here.

If you’ve not heard of v-bind I’d recommend visiting official Vue docs or a simplified article I wrote focusing on Vue Directives.

What do I mean by dynamically?

Remember how we used expressions with <h1> {{ message }} </h1> ?

Well, the text behind ‘message’ lives somewhere else doesn’t it? It’s not set within our <h1> tags. So we’re ‘getting it’ from somewhere else’ 🤔

Example of static value:

<purple-paragraph 
  title="Title of first paragraph"> 
</purple-paragraph>

This is what would happen if we wanted to display titles of blog posts for example. There are many posts and they all have different titles, so we can’t just display ‘Title’ can we? Let’s see how can we overcome this together 😜

Example of dynamic value:

<!-- Dynamically assign the value of a variable -->
<blog-post 
  :title="post.title"> 
</blog-post>

<!-- Dynamically assign the value of a complex expression -->
<blog-post 
  :title="post.title + ' by ' + post.author.name">
</blog-post>

Let’s break it down:

On the top line we added ‘title’ field to our blog post component and the value within it changes. We can see it changes because we see an object ‘post’ with a ‘.title’ behind it. This means every post will for sure keep their titles and we won’t just set a ‘static text’ for all of them.

On the bottom line we also added ‘title’ field to our blog post component but we also added another object (post.author.name) and an additional ‘normal word’ (by) wrapped up with empty space on each side.

This makes it a complex expression. 😀

To recap: we register a prop, we can give it a type and then we need to add it to our HTML block and set value we wanted it to have. That’s it 🥳

I believe this is enough for the day so we’ll go deeper in another section and celebrate what we’ve learned today 🤗

REMINDER: Question Time: What would be better?

1. To have 500 different component files within your component folder
2. To have few components that hold 500 lines of code each

Let me know your thoughts down in the comment section 

I’m REALLY interested in how’s your Vue learning going so far so please make sure to let me know your thoughts and show off your recent projects over on Instagram or my contact page 💛

Leave a Reply