Component Props In Vue.js/CLI

Today, we will learn about props in component, like which different types we can use for the props in component.

Define a prop inside the component

  • Props are the way components can accept data from components that include them (parent components).
  • When a component expects one or more prop, it must define them in its Props property:
<template>
  <p>{{ name }}</p>
</template>

<script>
export default {
  props: ['name']
}
</script>
  • The valid types you can use are:
    • String
    • Number
    • Boolean
    • Array
    • Object
    • Date
    • Function
    • Symbol
  • When a type mismatches, Vue.js alerts (in development mode) in the console with a warning.
  • Prop types can be more articulated.
  • You can allow multiple different value types:
props: {
  firstName: [String, Number]
}

Set a prop to be mandatory

  • You can require a prop to be mandatory:
props: {
  firstName: {
    type: String,
    required: true
  }
}

Set the default value of a prop

  • You can specify a default value:
props: {
  firstName: {
    type: String,
    default: 'Bhagvat'
  }
}
  • For objects:
props: {
  name: {
    type: Object,
    default: {
      firstName: 'Bhagvat',
      lastName: ''
    }
  }
}
  • Default can also be a function that returns an appropriate value, rather than being the actual value.
  • You can even build a custom validator, which is cool for complex data:
props: {
  name: {
    validator: name => {
      return name === 'Bhagvat' 
    }
  }
}

Passing props to the component

  • If it’s a data property, you use:
<template>
  <ComponentName :color=color />
</template>

<script>
...
export default {
  //...
  data: function() {
    return {
      color: 'white'
    }
  },
  //...
}
</script>

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories