![]() |
VOOZH | about |
Vue.js Props is an attribute to the configuration of the component. It is used to pass the data to the component to work dynamically. The props configuration defines the type of data it can receive from different components of Vue.
Table of Content
<script setup >
const student = defineProps([ 'name'] )
console.log(student.name )
</scirpt>
export default {
props: [ 'name']
}
// In script setup
defineProps({ name: String });
// In non scrpt setup
export default {
props: { name: String }
}
<script setup lang="ts">
defineProps<{
name ?: string
}>()
</script>
Refer to the Vue.js Props Declaration article for detailed description.
This facilitates the various components for the Props, such as Name Casing, Static vs. Dynamic Props, Passing Different Value Types, and Binding Multiple Properties Using an Object, which helps to manage & organize the Props in a structured manner in the Components.
In Vue.js, all the props are bonded between the child and properties are one-way-down. When we update the prop in the parent component it is updated to all the child components but the reverse does not happen and vue.js warns the use.
Cases When child component tries to change Props:
props = defineProps(['props1']);
// Variable intialize with props value
temp = props1;
props = defineProps(['firstName', 'lastName']);
// Applying computed property on props
fullName = computed(() => firstName + lastName);
Mutating Object / Array Props
Vue.js does not prevent the array and object mutation because the array and object are passed as a reference to the child and prevention is expensive as compared to others.
Components can specify the criteria for their props, including their types. If these criteria are not met, Vue will issue a warning in the JavaScript console of the browser. This is typically valuable while generating the component meant for consumption by other developers.
Props with boolean type mimic the behavior of native boolean attributes.
// This is equal to Enable = true
<Component Enable />
// This is equal to Enable false
<Component />
When we allow multiple props Boolean casting is also applied.
// True is casted
defineProps({
Enable: [Boolean, Number]
})
// True is casted
defineProps({
Enable: [Boolean, String]
})
// True is casted
defineProps({
Enable: [Number, Boolean]
})
// Absence of Enable will casted as empty string Enable=""
defineProps({
Enable: [String, Boolean]
})
// Using script setup
<script setup>
const props = defineProps(['data1', 'data2', ...]);
</script>
// Using non script setup
<script>
export default{
props: [ 'data1', 'data2'... ]
}
Example 1: In this example, we will pass name, course, age, and batch as props data and print it. Vue.js project files are:
Output:
Example 2: In this example, we will define props with script setup. We will pass props data to the component and show it on the mouse click event.
Output: