Vue.js component props

Props are used to pass state to child components. Know all about them

Define props inside the component

Props are the way components can receive data from the component that contains them (the parent component).

When a component requires one or more props, they must be defined in itpropsproperty:

Vue.component('user-name', {
  props: ['name'],
  template: '<p>Hi {{ name }}</p>'
})

Or, in the Vue single file component:

<template>
  <p>{{ name }}</p>
</template>

<script> export default { props: [‘name’] } </script>

Accept multiple props

You can have multiple props by appending multiple props to the array:

Vue.component('user-name', {
  props: ['firstName', 'lastName'],
  template: '<p>Hi {{ firstName }} {{ lastName }}</p>'
})

Set prop type

You can specify the type of props by using an object instead of an array, using the property name as the key for each property, and using the type as the value:

Vue.component('user-name', {
  props: {
    firstName: String,
    lastName: String
  },
  template: '<p>Hi {{ firstName }} {{ lastName }}</p>'
})

The valid types you can use are:

  • String
  • digital
  • Boolean
  • Large numbers
  • purpose
  • date
  • Features
  • Symbol

When the types do not match, Vue warns in the console in a warning mode (in development mode).

The type of props can be expressed more clearly.

You can allow many different value types:

props: {
  firstName: [String, Number]
}

Set props as mandatory

You can require props to be mandatory:

props: {
  firstName: {
    type: String,
    required: true
  }
}

Set the default value of the prop

You can specify a default value:

props: {
  firstName: {
    type: String,
    default: 'Unknown person'
  }
}

For the object:

props: {
  name: {
    type: Object,
    default: {
      firstName: 'Unknown',
      lastName: ''
    }
  }
}

defaultIt can also be a function that returns an appropriate value instead of the actual value.

You can even build a custom validator that is cool for complex data:

props: {
  name: {
    validator: name => {
      return name === 'Flavio' //only allow "Flavios"
    }
  }
}

Pass props to components

You pass the prop to the component using the following syntax

<ComponentName color="white" />

If you are passing a static value.

If it is a data attribute, use

<template>
  <ComponentName :color=color />
</template>

<script> … export default { //… data: function() { return { color: ‘white’ } }, //… } </script>

You can use the ternary operator within the prop value to check the true condition and pass the value that depends on the condition:

<template>
  <ComponentName :colored="color == 'white' ? true : false" />
</template>

<script> … export default { //… data: function() { return { color: ‘white’ } }, //… } </script>

Download mine for freeVue manual


More vue tutorials: