- 笔记73
- frontend53
- vue28
- backend17
- theme11
- pinia10
- edu6
- code-snippets6
- 小学4
- playground4
- linux4
- devops3
- docker2
- dev1
- 家装1
- armbian1
- 路由器1
- echarts1
- tools1
Actions are the equivalent of methods in components.
They can be defined with the actions property in defineStore()
and they are perfect to define business logic.
Like getters, actions get access to the whole store instance through this
with full typing (and autocompletion ✨) support.
Unlike getters, actions
can be asynchronous, you can await inside of actions any API call or even other actions!
A store is defined using defineStore()
and that it requires a unique name, passed as the first argument:
import { defineStore } from 'pinia'
// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
export const useStore = defineStore('main', {
// other options
})
Getters are exactly the equivalent of computed values for the state of a Store.
They can be defined with the getters property in defineStore()
.
They receive the state as the first parameter to encourage the usage of arrow function:
we can get access to the whole store instance through this
when defining a regular function,
but it is necessary to define the type of the return type (in TypeScript).
Pinia stores can be fully extended thanks to a low level API. Here is a list of things you can do:
- Add new properties to stores
- Add new options when defining stores
- Add new methods to stores
- Wrap existing methods
- Change or even cancel actions
- Implement side effects like Local Storage
- Apply only to specific stores
The state is, most of the time, the central part of your store.
In Pinia the state is defined as a function that returns the initial state.
import { defineStore } from 'pinia'
const useStore = defineStore('storeId', {
// arrow function recommended for full type inference
state: () => {
return {
// all these properties will have their type inferred automatically
counter: 0,
name: 'Eduardo',
isAdmin: true,
}
},
})
Installation
Create a pinia (the root store) and pass it to the app:
import { createPinia } from 'pinia'
app.use(createPinia())
Pinia (pronounced /piːnjʌ/, like "peenya" in English) is a store library for Vue, it allows you to share a state across components/pages.
- Works for both Vue 2 and Vue 3
- Optional composition API
- The same API for SSR.
- TypeScript support
- Hot module replacement
- Plugins