How to pass value to child component in Vue.js
Hello buddy, in this blog we will see how we can pass value to the child component in vue.js and we will also learn the use of props.
Sharing data across components is one of the core functionalities of VueJS. It allows you to design a more modular project, control data scopes, and create a natural flow of data across your app.
Think you are using the Vue tab component where you have put 5oo lines of component, at that time we will need to create a child component so that we can share the code with multiple components.
Unless you’re creating your entire Vue app in one component (which wouldn’t make any sense), you’re going to encounter situations where you need to share data between components.
Let’s Suppose I have two Vue js components, one name is AccountInfo.Vue and another name is ProfilePage.vue.
AccountInfo.vue is our child component and ProfilePage.vue is our parent component. Child component means we will import this AccountInfo.vue in ProfilePage.vue.
Child Component Code
// AccountInfo.vue
<template>
<div id='account-info'>
{{username}}
</div>
</template>
<script>
export default {
props: ['username']
}
</script>
In the above code, you have seen that I have passed username as the props, we will pass the same prop name via our parent component.
Parent Component Code
<template>
<div>
<account-info :username="user.username" />
</div>
</template>
<script>
import AccountInfo from "@/components/AccountInfo.vue";
export default {
components: {
AccountInfo
},
data() {
return {
user: {
username: 'matt'
}
}
}
}
</script>
Here in the account-info component, you have seen, that we have passed the username, this is the way where the child component can access the parent component value.
Now I think you have the basic idea that how to pass value to child component in Vue.js