Vue, Web Dev, Cheat Sheet, Notes โ Feb 1, 2024 ๐ 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"); Copy 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> Copy <script setup> import {useCounterStore} from '@/stores/counter'; const storeCounter = useCounterStore(); </script> Copy 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, }; }); Copy 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--; }, }, }); Copy