0
0
Vueframework~5 mins

Using stores in components in Vue

Choose your learning style9 modes available
Introduction

Stores help keep data shared and organized across different parts of your app. Using stores in components makes it easy to read and change this shared data.

You want multiple components to share the same data and update together.
You need to keep track of user login status across pages.
You want to manage a shopping cart that many components can add to or show.
You want to keep app settings consistent everywhere.
You want to avoid passing data through many layers of components.
Syntax
Vue
<script setup>
import { useStore } from '@/stores/storeName'
const store = useStore()
</script>
Use useStore() to access the store inside your component.
Make sure your store is properly defined and exported in your stores folder.
Examples
This example imports a counter store and sets it up for use in the component.
Vue
<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
</script>
Here, the component shows a button that displays and updates the count from the store.
Vue
<template>
  <button @click="counterStore.increment">Count: {{ counterStore.count }}</button>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
</script>
Sample Program

This component uses a Pinia store to keep a count. The buttons let you add 1 or reset the count. The count value updates everywhere the store is used.

Vue
<template>
  <div>
    <h2>Counter: {{ counterStore.count }}</h2>
    <button @click="counterStore.increment">Add 1</button>
    <button @click="counterStore.reset">Reset</button>
  </div>
</template>

<script setup>
import { defineStore } from 'pinia'

// Define the store (usually in a separate file)
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++
    },
    reset() {
      this.count = 0
    }
  }
})

const counterStore = useCounterStore()
</script>
OutputSuccess
Important Notes

Stores keep your data in one place, making your app easier to manage.

Always import and call your store inside <script setup> for Vue 3 Composition API.

Use actions in the store to change data instead of changing state directly.

Summary

Stores let components share and update data easily.

Import your store with useStore() inside components.

Use store state and actions to read and change shared data.