Pinia Store Explanation
March 9, 2025 ยท AI Conversations
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
explain above code
### 1. **Imports**
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
– `ref`: A Vue composition API function that creates a reactive reference.
– `computed`: Another composition API function that creates a reactive computed property.
– `defineStore`: A function from Pinia to define a new store.
### 2. **Defining the Store**
export const useCounterStore = defineStore('counter', () => {
– This creates a Pinia store named `'counter'`.
– The second argument is a function (setup-style store), meaning it returns state and functions.
### 3. **State: Reactive Count Variable**
const count = ref(0)
– `count` is a **reactive variable** initialized to `0`.
### 4. **Computed Property: `doubleCount`**
const doubleCount = computed(() => count.value * 2)
– `doubleCount` is a **computed property** that automatically updates when `count` changes.
– It returns `count * 2` dynamically.
### 5. **Mutation: Increment Function**
function increment() {
count.value++
}
– This function increases `count` by `1`.
### 6. **Returning the Store Properties**
return { count, doubleCount, increment }
– The store exposes:
– `count`: The reactive counter state.
– `doubleCount`: A computed property based on `count`.
– `increment()`: A function to update `count`.
—
### **Usage in a Vue Component**
To use this store inside a Vue component:
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment">Increment</button>
</div>
</template>
### **Summary**
– The `useCounterStore` provides a global reactive store.
– `count` holds the state.
– `doubleCount` is a computed property that depends on `count`.
– `increment()` modifies the state.
This is a simple example of **Pinia**, which replaces Vuex as the recommended state management library in Vue 3. ๐