vuejs
  1. vuejs-props

Vue.js Props

Syntax

Vue.component('my-component', {
  props: ['propA', 'propB'],
  // ...
})

Example

<div id="app">
  <my-component :prop-a="foo" :prop-b="bar"></my-component>
</div>
Vue.component('my-component', {
  props: ['propA', 'propB'],
  template: '<div>{{ propA }} {{ propB }}</div>'
})

new Vue({
  el: '#app',
  data: {
    foo: 'Hello',
    bar: 'World'
  }
})

Output

The output of the above example will be a div element containing the value of propA and propB:

Hello World

Explanation

Props are used to pass data to child components in Vue.js. The parent can pass data down to the child component by setting props in the child component's definition. The child component then receives the data as a prop and can use it to render its own template.

Use

Props in Vue.js are useful when you have a component that needs to receive data from its parent, but the data needs to be stored separately from the parent component's data. This allows for more modular and flexible components, as each component is responsible only for its own data and functionality. It also encourages reusability, as a component can be used in multiple places throughout an application, without having to manually create and pass down the same data to each instance of the component.

Important Points

  • Props in Vue.js are passed from the parent component to the child component using a : followed by the name of the prop.
  • Props are one-way data flow from parent to child components. If a child component needs to modify the passed data, it can emit an event to the parent and have the parent update the data.
  • Props are defined in the child component's props option, which is an array of strings that represent the names of the props the component expects to receive.
  • Props can be validated by setting their type, default value, and other options in the prop definition. This ensures that the data passed to the component meets certain requirements and avoids errors.

Summary

Props are a key feature of Vue.js, allowing data to be passed from parent components to child components with ease. Understanding how to define and use props in your components is essential for building modular and flexible Vue.js applications.

Published on: