1. Introduction
Introduction to Pinia
Pinia is Vue 3’s official state management library, designed to provide a simple, flexible and type-safe state management solution. Pinia has a similar design philosophy to Vuex, but is lighter and easier to use.
Advantages and applicable scenarios of Pinia
- Lightweight: The core code of Pinia is very streamlined and suitable for small and medium-sized projects.
- Type safety: Pinia fully supports TypeScript, providing better type inference and code prompts.
- flexibility:Pinia allows developers to create multiple stores as needed, and each store is independent.
The objectives and structure of this article
This article aims to fully analyze how Pinia is used in Vue 3 to add, modify and delete data, and help readers master these techniques with detailed code examples. The article structure is as follows:
- Introduce the basics and configuration of Pinia.
- Discuss how to add, modify, and delete data in Pinia.
- Provide performance optimization suggestions and practical cases.
2. Pinia Basics
Installation and configuration of Pinia
Pinia can be installed via npm or yarn.
Install Pinia
npm install pinia
Configure Pinia
// src/ import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './'; const app = createApp(App); (createPinia()); ('#app');
Create and use Store
Store is the core concept of Pinia, used to manage the state of an application.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), actions: { increment() { ++; }, }, });
Use Store in Components
<!-- src/components/ --> <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> </template> <script> import { useCounterStore } from '@/stores/counter'; export default { setup() { const counterStore = useCounterStore(); return { count: , increment: , }; }, }; </script>
Concepts of State, Getters and Actions
- State: Status data in the Store.
- Getters: Used to derive new data from State.
- Actions: Used to modify State or perform asynchronous operations.
3. Add data
Add data in the Store
Add data in the Store via State and Actions.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ users: [], }), actions: { addUser(user) { (user); }, }, });
Add data using Actions
Encapsulate the logic of adding data through Actions.
Sample code
<!-- src/components/ --> <template> <div> <input v-model="name" placeholder="Name" /> <input v-model="email" placeholder="Email" /> <button @click="addUser">Add User</button> </div> </template> <script> import { ref } from 'vue'; import { useUserStore } from '@/stores/user'; export default { setup() { const name = ref(''); const email = ref(''); const userStore = useUserStore(); const addUser = () => { if ( && ) { ({ name: , email: }); = ''; = ''; } }; return { name, email, addUser, }; }, }; </script>
Example: Add user data
Enter user information through the form and add it to the Store.
Sample code
<!-- src/components/ --> <template> <div> <AddUser /> <ul> <li v-for="user in users" :key="">{{ }} - {{ }}</li> </ul> </div> </template> <script> import { useUserStore } from '@/stores/user'; import AddUser from './'; export default { components: { AddUser, }, setup() { const userStore = useUserStore(); return { users: , }; }, }; </script>
4. Modify the data
Modify data in the Store
Modify data in the Store through State and Actions.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ users: [], }), actions: { updateUser(email, newData) { const user = (user => === email); if (user) { (user, newData); } }, }, });
Use Actions to modify data
Encapsulate the logic of modifying data through Actions.
Sample code
<!-- src/components/ --> <template> <div> <input v-model="name" placeholder="Name" /> <input v-model="email" placeholder="Email" /> <button @click="updateUser">Update User</button> </div> </template> <script> import { ref } from 'vue'; import { useUserStore } from '@/stores/user'; export default { setup() { const name = ref(''); const email = ref(''); const userStore = useUserStore(); const updateUser = () => { if ( && ) { (, { name: }); = ''; = ''; } }; return { name, email, updateUser, }; }, }; </script>
Example: Modify user data
Modify user information through the form and update it to the Store.
Sample code
<!-- src/components/ --> <template> <div> <AddUser /> <EditUser /> <ul> <li v-for="user in users" :key="">{{ }} - {{ }}</li> </ul> </div> </template> <script> import { useUserStore } from '@/stores/user'; import AddUser from './'; import EditUser from './'; export default { components: { AddUser, EditUser, }, setup() { const userStore = useUserStore(); return { users: , }; }, }; </script>
5. Delete data
Delete data in the Store
Delete data in the Store via State and Actions.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ users: [], }), actions: { deleteUser(email) { = (user => !== email); }, }, });
Use Actions to delete data
Encapsulate the logic of deleting data through Actions.
Sample code
<!-- src/components/ --> <template> <div> <AddUser /> <EditUser /> <ul> <li v-for="user in users" :key=""> {{ }} - {{ }} <button @click="deleteUser()">Delete</button> </li> </ul> </div> </template> <script> import { useUserStore } from '@/stores/user'; import AddUser from './'; import EditUser from './'; export default { components: { AddUser, EditUser, }, setup() { const userStore = useUserStore(); const deleteUser = (email) => { (email); }; return { users: , deleteUser, }; }, }; </script>
Example: Delete user data
Delete user information via buttons and remove it from the Store.
Sample code
<!-- src/components/ --> <template> <div> <AddUser /> <EditUser /> <ul> <li v-for="user in users" :key=""> {{ }} - {{ }} <button @click="deleteUser()">Delete</button> </li> </ul> </div> </template> <script> import { useUserStore } from '@/stores/user'; import AddUser from './'; import EditUser from './'; export default { components: { AddUser, EditUser, }, setup() { const userStore = useUserStore(); const deleteUser = (email) => { (email); }; return { users: , deleteUser, }; }, }; </script>
6. Advanced usage of Pinia
Extend Pinia with plug-ins
Pinia supports extensions through plug-ins, such as persistent storage.
Sample code
// src/plugins/ export function piniaPlugin(context) { const store = ; store.$subscribe((mutation, state) => { (store.$id, (state)); }); const savedState = (store.$id); if (savedState) { store.$patch((savedState)); } } // src/ import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './'; import { piniaPlugin } from './plugins/piniaPlugin'; const pinia = createPinia(); (piniaPlugin); const app = createApp(App); (pinia); ('#app');
Use watch to monitor State changes
passwatch
Listen to changes in State and execute corresponding logic.
Sample code
import { watch } from 'vue'; import { useUserStore } from '@/stores/user'; export default { setup() { const userStore = useUserStore(); watch( () => , (newUsers) => { ('Users updated:', newUsers); }, { deep: true } ); }, };
Example: Implement the undo/redo function
Undo/redo via plug-ins and State listening.
Sample code
// src/plugins/ export function undoRedoPlugin(context) { const store = ; const history = []; let future = []; store.$subscribe((mutation, state) => { (((state))); future = []; }); = () => { if ( > 1) { (()); store.$patch(history[ - 1]); } }; = () => { if ( > 0) { const nextState = (); (nextState); store.$patch(nextState); } }; } // src/ import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './'; import { undoRedoPlugin } from './plugins/undoRedoPlugin'; const pinia = createPinia(); (undoRedoPlugin); const app = createApp(App); (pinia); ('#app');
7. Pinia's performance optimization
Avoid unnecessary State updates
pass$patch
Batch updates to State to avoid unnecessary rendering.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ users: [], }), actions: { addMultipleUsers(users) { this.$patch((state) => { (...users); }); }, }, });
Optimize Getters using computed
passcomputed
Cached derived data to avoid repeated calculations.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ users: [], }), getters: { activeUsers: (state) => (user => ), }, });
Example: Optimize data operation performance
Optimize data operation performance with batch updates and caches.
Sample code
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ users: [], }), actions: { addMultipleUsers(users) { this.$patch((state) => { (...users); }); }, }, getters: { activeUsers: (state) => (user => ), }, });
8. Testing and debugging of Pinia
Test the Pinia Store with Vitest
Test the functionality of the Pinia Store with Vitest.
Sample code
// tests/stores/ import { setActivePinia, createPinia } from 'pinia'; import { useUserStore } from '@/stores/user'; describe('User Store', () => { beforeEach(() => { setActivePinia(createPinia()); }); test('addUser adds a user to the store', () => { const userStore = useUserStore(); ({ name: 'John', email: 'john@' }); expect().toHaveLength(1); }); });
Debug Pinia with Vue Devtools
Debug the status and operations of the Pinia Store with Vue Devtools.
Sample code
// Use Debugging in Componentsexport default { setup() { const userStore = useUserStore(); ('Users:', ); }, };
9. Practical cases
Implement a user management system
Implement a user management system through Pinia, which supports adding, modifying and deleting users.
Sample code
<!-- src/components/ --> <template> <div> <AddUser /> <EditUser /> <UserList /> </div> </template> <script> import AddUser from './'; import EditUser from './'; import UserList from './'; export default { components: { AddUser, EditUser, UserList, }, }; </script>
This is the article about Vue3's operation code for data addition, modification and deletion. For more information about Vue3 pinnia, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!