Introduction

Vue.js provides a powerful feature for validating props passed to child components, which is crucial for ensuring data integrity in your application. Props validation helps you catch and prevent unexpected data from entering your components.


Sample Code

Let's create a simple example to illustrate props validation in Vue.js. We'll create a reusable button component that expects a "color" prop with predefined values:


<div id="app">
<custom-button color="primary">Primary Button</custom-button>
<custom-button color="secondary">Secondary Button</custom-button>
<custom-button color="invalid-color">Invalid Button</custom-button>
</div>

Now, define the "custom-button" component and specify props validation using the "props" option:


Vue.component('custom-button', {
props: {
color: {
type: String,
validator: function(value) {
return ['primary', 'secondary'].includes(value);
},
required: true
}
},
template: '<button :class="color"><slot></slot></button>'
});

In this code:

  • We define the "color" prop and specify it as a String.
  • We use the "validator" function to ensure that the value is either 'primary' or 'secondary'.
  • We set "required" to true to indicate that the "color" prop is mandatory.

Now, when we try to use the "custom-button" component with an "invalid-color," Vue.js will throw an error, ensuring data integrity.