How to share data between two components in VueJS

The code function of using the VueJS framework is that it allows sharing of data between two components. This makes up a more modular design for your project, has control data scopes, and creates a more natural flow of data across your application. There are many situations where you need to share data between two components in a VueJS project. Let us go through one such example.

How to share data between components

1. Using Props

Props are the custom attributes we can give to a component. So we can give those attributes values in our templates when passing data from a parent to a child component.

For example, we are working on a user profile page and want the child component to accept a username prop. We will need two components.

The child component that accepts the prop. For example, AccountDetails.vue.

// AccountDetails.vue

<template>
 <div id='account-info'>
   {{username}}
 </div>
</template>
 
<script>
export default {
 props: ['username']
}
</script>

The parent component that passes the prop. For example, ProfileInfo.vue.

// ProfileInfo.vue
 
<account-info username='alice' />

When the page loads, we will see the AccountDetails component that properly renders the value passed in by its parent.

We can use v-bind to dynamically pass props when working with VueJS directives. For example, if we want to set the username prop to be equal to a variable. We can do this by using a shorthand for the v-bind directive as shown below.

<template>
 <div>
   <account-info :username="user.username" />
 </div>
</template>
 
<script>
import AccountDetails  from "@/components/AccountDetails.vue";
 
export default {
 components: {
   AccountDetails 
 },
 data() {
   return {
     user: {
       username: 'matt'
     }
   }
 }
}
</script>

You can use the props value anywhere else in a component file like the v-model.

2.Using routes

Query parameters and router parameters work in a similar way in Vue.js. You can pass query and router parameters with a router-link as shown below.

<template>
    <router-link :to="{ name: 'AccountDetails', params: { data: 'your_value' } }">Go to another component with data</router-link>
</template>

This allows sharing of data in the query parameters between two components using router-link in a VueJS application.