1. Install Pinia
1. Install using npm
In the project directory, execute the following command from the command line:
npm install pinia
2. Use Pinia in Vue application
Introduce and use Pinia in (or entry file). First import the createPinia function and create a Pinia instance, and then mount it on the Vue app.
import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './'; const pinia = createPinia(); const app = createApp(App); (pinia); ('#app');
2. Define the store
1. Define a simple store
Create a new .js file (for example) to define the store.
import { defineStore } from 'pinia'; // The first parameter is the unique ID of the store, and the second parameter is a function, which returns the configuration object of the storeexport const useCounterStore = defineStore('counter', { // Similar to state in Vuex, storing data state: () => { return { count: 0 }; }, // Similar to getters in Vuex, used to derive data getters: { doubleCount: (state) => { return * 2; } }, // Similar to the combination of actions and mutations in Vuex, used to modify state actions: { increment() { ++; }, decrement() { --; } } });
3. Use store in components
1. Get the store instance in the component and use the data
In Vue components, you can use the useCounterStore function to get the store instance.
<template> <div> <p>Current count: {{ }}</p> <p>Double count: {{ }}</p> <button @click="()">Increasing the count</button> <button @click="()">Reduce count</button> </div> </template> <script> import { useCounterStore } from './'; export default { setup() { const counter = useCounterStore(); return { counter }; } }; </script>
2. Use store outside the component (for example, in non-component code such as routing guards)
You can directly import the store definition and use it.
import { useCounterStore } from './'; const counterStore = useCounterStore(); (); ();
Pinia provides a simple and intuitive way to manage state in Vue 3 applications, which has the advantages of a simpler API and better type support compared to Vuex.
This is the end of this article about how to use pinia in vue3. For more related content of vue3 pinia, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!