Sending Variables Between Components Using Props in Vue.js

In this article, I’m gonna show how to send variables from parent to child using props. In Vue.js there is different ways to send variables between components but I will talk about only props in this article.

Props is best and efficient way to send variables between components but props only send from parent to child. This means you can only send props where you call your component (parent) to the your component (child). So you can’t send props from child to parent. But of course there is way to do this. We are calling this way Emitting but I said we are not talking about Emitting in this article.

As you will see below I am in a page named forgot.vue and here I calling nx-text component in nuxt-link tag. I using Nuxt.js in this project but you don’t need to Nuxt.js for passing props. nuxt-link tag is belong to Nuxt.js. Doesn’t effect our component.

My nx-text component seems like this;

As you will see above I define a text object in props object. We describe text prop’s type by saying type. We need to type a default value in order not to have trouble in a situation where no value comes from the parent.

Not: If you don’t want to type default value you can describe required or not. This means if parent don’t send text prop to the child your code will be give error in console. (If you type “required: false” your code will be give error again because your code doesn’t have default value in this situation. This is not recommended.)

You need to send variable when “required: true”.

You can use the variable from prop like you use the variable from the data function;

You can use like {{ variable_name }}.

In the parent side things easier:

We are sending like text=”Back”

We type “ text=”String Value” ” like writing a html parameter in where we calling component. If you will send a variable from data function , a Boolean value or a Number value you need to type like this;

“alternative_text” is a string value in data function.

Like this we successfully send variable to the child component from parent component.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yusufcan Yılmaz

Yusufcan Yılmaz

I created my first website at 12 years old. After that I learned how to develop web fronted and now striving to build upon what I know about Frontend.