๐Ÿ“š Pinia State Management

๐Ÿ“š Pinia State Management

Initialize Pinia for your app

// /src/main.js

import "./assets/main.css";

import { createApp } from "vue";
import { createPinia } from "pinia"; // here ๐Ÿ‘ˆ

import App from "./App.vue";

const app = createApp(App);

app.use(createPinia()); // here ๐Ÿ‘ˆ
app.mount("#app");

Use the store

<template>
  <div class="counter-container">
    <!-- state (data) -->
    <h2>{{ storeCounter.count }}</h2>

    <!-- actions (methods)-->
    <button @click="storeCounter.increaseCount">+</button>
    <button @click="storeCounter.decreaseCount">-</button>
  </div>

  <!-- getters (computed) -->
  <div>The counter is {{ storeCounter.oddOrEven }}</div>

  <!-- two-way data binding-->
  <input v-model="storeCounter.count" type="number" />
</template>
<script setup>
  import {useCounterStore} from '@/stores/counter'; const storeCounter =
  useCounterStore();
</script>

Define the store (Composition API)

  • composition api store
import { ref, computed } from "vue";
import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", () => {
  // State
  const count = ref(0);

  // Getters
  const doubleCount = computed(() => count.value * 2);
  const oddOrEven = computed(() => (count.value % 2 === 0 ? "even" : "odd"));

  // Actions
  function increaseCount() {
    count.value++;
  }

  function decreaseCount() {
    count.value--;
  }

  // Expose the state, getters, and actions
  return {
    count,
    doubleCount,
    oddOrEven,
    increaseCount,
    decreaseCount,
  };
});

Define the store (Options API)

  • options api store
import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", {
  // State
  state: () => ({
    count: 0,
  }),

  // Getters
  getters: {
    oddOrEven: (state) => (state.count % 2 === 0 ? "even" : "odd"),
  },

  // Methods (Actions)
  actions: {
    increaseCount() {
      this.count++;
    },
    decreaseCount() {
      this.count--;
    },
  },
});