Component Props

Published on Sep 10, 2022

Custom attributes to pass data into a component.

Given a component:

components/PlaceholderImage.js

app.component('placeholder-image', {
  // component options
  template: '<img src="https://picsum.photos/200/300" />'
})

We might want to pass in the width & height for our custom image, something like:

index.html

...
<placeholder-image :width="customWidth" :height="customHeight"></placeholder-image>
...

We'll add the 2 attributes as props:

components/PlaceholderImage.js

app.component('placeholder-image', {
  props: ['width', 'height'],
  template: '<img :src="src" />',
  computed: {
    src() {
      return `https://picsum.photos/${this.width}/${this.height}`
    }
  }
})

We're now also using a computed property to generate the image src.

Validation

We can validate the props using the type property:

components/PlaceholderImage.js

app.component('placeholder-image', {
  props: {
    width: {
      type: Number,
      required: true
    },
    height: {
      type: Number,
      required: true
    }
  },
  template: '<img :src="src" />',
  computed: {
    src() {
      return `https://picsum.photos/${this.width}/${this.height}`
    }
  }
})