Passing Data via Props in Vue.Js

Yahya Gok
3 min readMay 23, 2021

--

Props are how you pass data from one component to another, as parameters.

In Vue, props (or properties), are the way that we pass data from a parent component down to it’s child components.

When we build our applications out of components, we end up building a data structure called a tree. Similar to a family tree, you have:

  • parents
  • children
  • ancestors
  • and descendants

Data flows down this tree from the root component, the one at the very top. Sort of like how genetics are passed down from one generation to the next, parent components pass props down to their children.(1)

Let’s explain this concept with an example.

I have a project that shows all the jokes that in a url, I have all the jokes in my top component which I called index.vue, which is inside my pages folder and then jokes then id older, pages >> jokes >> _id > index.vue.

I use data and created method to get all the data from resource, and all the jokes will be inside the jokes array in line 23, on the below picture. Obviously,

we need to carry those jokes to joke component, as we do in similar to react.js. We want to separate the job, so it will make our job easier.

once we get all the jokes to an array, we are ready to send those to another component. I created a component called joke component inside components folder. after creating that folder I added line 7(below picture)to our index.vue file to

<Joke v-for=”joke in jokes” :key=”joke.id” :id=”joke.id” :joke=”joke.joke”

/>

So, this <joke /> is sembolize that this is child component to our parent component which is index.vue.

v-for=”joke in jokes” is just a way like using .map method, joke in jokes is making each index in an array to joke. Each joke has id and joke property as you can as see below picture. Here on;

<Joke v-for=”joke in jokes” :key=”joke.id” :id=”joke.id” :joke=”joke.joke”

/>

I’m just taking these two properties to send <Joke /> component, doing this;

:id=”joke.id” :joke=”joke.joke”

After we do this we need two more things to do;

one is line 13 on above picture;

import Joke from ‘../../components/Joke’;

and this export default;

export default {

components: {

Joke,

}

That is all we do in index.vue.

Last thing we should do on the joke component is to add props [‘joke, ;id]

export default {

name: “Joke”,

props: [‘joke’, ‘id’ ]

}

I watched traversy media’s one of video and this concept explained well there.

Resources

resource(1) from

--

--

Yahya Gok
Yahya Gok

No responses yet