Props vs Data in Vue.js with the help of Examples
In this tutorial, we are going to learn about the difference between props and data in vue with the help of examples.
Props
-
Props are used to pass the data to child components from parent components.
-
Props are read-only (We can’t mutate props).
-
Props are registered inside vue components by using
props
property.
Example:
<template>
<h1>Welcome {{name}}</h1></template>
<script>
export default{
props:['name'] //name prop is registered }
</script>
In this example, we registered name
inside Welcome
component, registered props can be used just like data properties inside a template.
Let’s pass the data to Welcome
component.
<template>
<div id="app">
<Welcome name="Gowtham"/> </div>
</tempalte>
Here we passed data to the Welcome
component by using name
prop.
Data
The data we defined inside vue components are independent to that component, so that we can’t access or mutate the data from other components.
The only way to access the component data from the other components is by using props
.
Data is mutable in vue.js so that if we update the data properties vue will automatically re-render your component with the updated changes.
Example:
Let’s consider we have two components named Welcome.vue
and App.vue
.
<template>
<h1>Welcome {{name}}</h1></template>
<script>
export default{
props:['name'] //name prop is registered }
</script>
<template>
<div>
<Welcome :name="name" /> <button @click="changeName">Change name</button>
</div>
</template>
<script>
import Welcome from "./welcome.vue";
export default {
data: function() {
return {
name: "Gowtham" };
},
methods: {
changeName() {
this.name = "Vue";
}
},
components: { Welcome }
};
</script>
In the App
component we passed data property name
to the Welcome
component using name
prop.
Now if we click on Change name
button the name
is property is updated so that the Welcome
component prop is also updated with the new value.
Have you observed one thing the data property of an App
component will be the prop
to the Welcome
component?
Conclusion
-
Data is private to the components and we can access that data from other components with the help of props.
-
Data is mutable and props are read-only.