← Back to Vue.js Course | Chapter 8: State Management | Lesson 3 of 6

Defining stores

defineStore creates a store with a unique id and its state, getters and actions.

In this page:

  1. Defining stores
Syntax
markup
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

markup
<!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
  1. Reusing the same id for two stores
  2. Making state an object instead of a function
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.