Defining stores
defineStore creates a store with a unique id and its state, getters and actions.
In this page:
Syntax
import { defineStore } from 'pinia';
export const useStoreName = defineStore('store-id', {
state: () => ({ property: value }),
getters: {},
actions: {}
});
Defining stores
defineStore("id", options) returns a function that gives you the store instance. The options form has state (a function), getters and actions, mirroring the Options API.
A setup-style form uses ref, computed and functions and mirrors the Composition API.
Note:
Name the returned function useSomethingStore by convention.
Example: Defining stores
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/[email protected]/lib/index.iife.js"></script>
<script src="https://unpkg.com/pinia@2/dist/pinia.iife.js"></script>
</head>
<body>
<div id="app"><p>{{ user.name }} / {{ user.loggedIn }}</p></div>
<script>
const useUserStore = Pinia.defineStore("user", {
state: () => ({ name: "Guest", loggedIn: false }),
getters: { label: (state) => state.name.toUpperCase() },
actions: { login(name) { this.name = name; this.loggedIn = true; } },
});
const app = Vue.createApp({ setup() { return { user: useUserStore() }; } });
app.use(Pinia.createPinia());
app.mount("#app");
console.log("store id:", useUserStore().$id, "| keys:", Object.keys(useUserStore().$state));
</script>
</body>
</html>
<!-- Output:
Rendered: Guest / false
console: store id: user | keys: name,loggedIn
-->
Live Example
Related Topics
Common Mistakes
- Reusing the same id for two stores
- Making state an object instead of a function
- Calling the store outside a Pinia context
Chapter Summary
- defineStore(id, options)
- state is a function
- getters and actions are supported
- Name it useXStore
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: