How to pass data to a component in Vue.js

in Code Write a comment

In this tutorial, you’ll learn the basics of passing data to child components with Props.

In Vue.js, components can have custom attributes (Props). You can register props on a component and pass a value to them.

Consider this example, we have a page (Products.vue) with a list of tech products. Each product has a product card, which shows the product title and featured image.

new Vue({
  el: "#app",
  data: {
    products: [
      { title: "Hololens", image: 'https://.../image.jpg' },
      { title: "Google Glass", image: 'https://.../image2.jpg' },
      { title: "PlayStation 5", image: 'https://.../image3.jpg' }
    ]
  }
})

Create a component in Vue.js

We can now create a <product-card> component and import it to our Products.vue component.

Vue.component('product-card', {
  props: ['product'],
  template: `
    <div class="product-card">
      <h3>{{ product.title }}</h3>
      <img :src="product.image"/>
    </div>
  `
})

Our <product-card> component accepts a single product prop, which can contain multiple product attributes (product title, image etc).


Hi, I'm Renat 👋

 


Render a list of objects by passing data with props

<product-card v-for="product in products" :product="product"></product-card>

The example above will render product cards by passing data to a child component with props. We’re using v-for to loop through products in our data object.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/pass-data-to-component-vue-js

PS: Make sure you check other Vue.js tutorials, e.g. how to make a DELETE request in Vue.js.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment