Communication between components in Vue.js with Pinia

In a Vue.js application, communication between components can become complex as the app grows. Pinia is the official store of Vue 3 and provides a simple and reactive way to share state between components. In this article, we will see how to use Pinia to facilitate communication between components.

Installing Pinia

To get started, you need to install Pinia and configure it in the Vue app.

npm install pinia

// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')

Creating a store

Let's create a store to share state between components. Suppose we want to share a counter.


// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})

Using the store in a component

Now we can use the store inside a component and modify its state.


<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <button @click="counter.increment">Increment</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()
</script>

Communication between components

With Pinia, multiple components can read from and write to the same store without needing to pass props or emit events.

Example of a second component that reads the state:


<template>
  <div>
    <h3>Current value: {{ counter.count }}</h3>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()
</script>

Both components share the same state reactively. When one component changes the value, the other automatically detects it.

Conclusion

Pinia greatly simplifies communication between Vue components, avoiding the need for complex solutions like event bus or prop drilling. It is reactive, modular, and easy to use, making it an excellent choice for state management in Vue 3 applications.

Back to top