export const useCounterStore = defineStore('counter', {
state: () => ({
- count: 0
+ count: 0,
}),
actions: {
increment() {
this.count++
- }
- }
+ },
+ },
})
```
```js
import { useUserStore } from '@/stores/user'
-import { createPinia } from 'pinia';
+import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
## Why should I use Pinia?
-<!--
+<!--
https://masteringpinia.com/lessons/why-use-pinia
-->
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
### direct %{#direct}%
-• **direct** = ``"direct"``
+• **direct** = `"direct"`
Direct mutation of the state:
- `store.$state.name = 'new name'`
- `store.list.push('new item')`
-___
+---
### patchFunction %{#patchfunction}%
-• **patchFunction** = ``"patch function"``
+• **patchFunction** = `"patch function"`
通过 `$patch` 和一个函数更改 state:
- `store.$patch(state => state.name = 'newName')`
-___
+---
### patchObject %{#patchobject}%
-• **patchObject** = ``"patch object"``
+• **patchObject** = `"patch object"`
通过 `$patch` 和一个对象更改 state:
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | `G` |
-| `A` | `A` |
+| 名称 | 类型 |
+| :--- | :--------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | `G` |
+| `A` | `A` |
## 层次结构 %{#hierarchy}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| 名字 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | `G` |
-| `A` | `A` |
+| 名字 | 类型 |
+| :--- | :--------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | `G` |
+| `A` | `A` |
## 层次结构 %{#hierarchy}%
action 的可选对象
-___
+---
### getters %{#getters}%
getter 的可选对象
-___
+---
### id %{#id}%
唯一的字符串密钥,用于识别整个应用中的 store。
-___
+---
### state %{#state}%
```ts
const useStore = defineStore('main', {
state: () => ({
- n: useLocalStorage('key', 0)
+ n: useLocalStorage('key', 0),
}),
hydrate(storeState, initialState) {
// @ts-expect-error: https://github.com/microsoft/TypeScript/issues/43826
storeState.n = useLocalStorage('key', 0)
- }
+ },
})
```
#### 参数
-| 名字 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `storeState` | `UnwrapRef`<`S`\> | the current state in the store |
-| `initialState` | `UnwrapRef`<`S`\> | initialState |
+| 名字 | 类型 | 描述 |
+| :------------- | :---------------- | :----------------------------- |
+| `storeState` | `UnwrapRef`<`S`\> | the current state in the store |
+| `initialState` | `UnwrapRef`<`S`\> | initialState |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| Name | Type |
-| :------ | :------ |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
-| `Store` | `Store` |
+| Name | Type |
+| :------ | :--------------------------------------------------- |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
+| `Store` | `Store` |
## 层次结构 %{#hierarchy}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| 名字 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | `G` |
-| `A` | `A` |
+| 名字 | 类型 |
+| :--- | :--------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | `G` |
+| `A` | `A` |
## 层次结构 %{#hierarchy}%
-- `Omit`<[`DefineStoreOptions`](pinia.DefineStoreOptions.md)<`Id`, `S`, `G`, `A`\>, ``"id"`` \| ``"actions"``\>
+- `Omit`<[`DefineStoreOptions`](pinia.DefineStoreOptions.md)<`Id`, `S`, `G`, `A`\>, `"id"` \| `"actions"`\>
↳ **`DefineStoreOptionsInPlugin`**
否则使用传递给 `defineStore()` 的对象。
如果没有定义 action,则默认为一个空对象。
-___
+---
### getters %{#getters}%
Omit.getters
-___
+---
### state
```ts
const useStore = defineStore('main', {
state: () => ({
- n: useLocalStorage('key', 0)
+ n: useLocalStorage('key', 0),
}),
hydrate(storeState, initialState) {
// @ts-expect-error: https://github.com/microsoft/TypeScript/issues/43826
storeState.n = useLocalStorage('key', 0)
- }
+ },
})
```
#### 参数
-| 名字 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `storeState` | `UnwrapRef`<`S`\> | the current state in the store |
-| `initialState` | `UnwrapRef`<`S`\> | initialState |
+| 名字 | 类型 | 描述 |
+| :------------- | :---------------- | :----------------------------- |
+| `storeState` | `UnwrapRef`<`S`\> | the current state in the store |
+| `initialState` | `UnwrapRef`<`S`\> | initialState |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
##### 参数
-| Name | Type |
-| :------ | :------ |
+| Name | Type |
+| :---- | :------------ |
| `app` | `App`<`any`\> |
##### 返回值
`void`
-___
+---
### state %{#state}%
#### 参数 %{#paramters}%
-| Name | Type | Description |
-| :------ | :------ | :------ |
+| Name | Type | Description |
+| :------- | :------------------------------------ | :------------------ |
| `plugin` | [`PiniaPlugin`](pinia.PiniaPlugin.md) | store plugin to add |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` = `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | [`_GettersTree`](../modules/pinia.md#_getterstree)<`S`\> |
-| `A` | [`_ActionsTree`](../modules/pinia.md#_actionstree) |
+| 名称 | 类型 |
+| :--- | :-------------------------------------------------------------------------------------------------- |
+| `Id` | extends `string` = `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | [`_GettersTree`](../modules/pinia.md#_getterstree)<`S`\> |
+| `A` | [`_ActionsTree`](../modules/pinia.md#_actionstree) |
## Accessors %{#accessors}%
#### 参数
-| Name | Type |
-| :------ | :------ |
+| Name | Type |
+| :------ | :------------------------------------------------------------------------- |
| `value` | `RouteLocationNormalizedLoaded` \| `Ref`<`RouteLocationNormalizedLoaded`\> |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
+| 名称 | 类型 |
+| :--- | :-------------------------------------------------------------------------------------------------- |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------ |
| `context` | [`PiniaPluginContext`](pinia.PiniaPluginContext.md)<`string`, [`StateTree`](../modules/pinia.md#statetree), [`_GettersTree`](../modules/pinia.md#_getterstree)<[`StateTree`](../modules/pinia.md#statetree)\>, [`_ActionsTree`](../modules/pinia.md#_actionstree)\> | Context |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| Name | Type |
-| :------ | :------ |
-| `Id` | extends `string` = `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | [`_GettersTree`](../modules/pinia.md#_getterstree)<`S`\> |
-| `A` | [`_ActionsTree`](../modules/pinia.md#_actionstree) |
+| Name | Type |
+| :--- | :-------------------------------------------------------------------------------------------------- |
+| `Id` | extends `string` = `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | [`_GettersTree`](../modules/pinia.md#_getterstree)<`S`\> |
+| `A` | [`_ActionsTree`](../modules/pinia.md#_actionstree) |
## 属性
用 `Vue.createApp()`创建的当前应用。
-___
+---
### options %{#options}%
调用 `defineStore()` 时定义 store 的初始选项。
-___
+---
### pinia %{#pinia}%
pinia 实例
-___
+---
### store %{#store}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` = `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | [`_GettersTree`](../modules/pinia.md#_getterstree)<`S`\> |
-| `A` | [`_ActionsTree`](../modules/pinia.md#_actionstree) |
+| 名称 | 类型 |
+| :--- | :-------------------------------------------------------------------------------------------------- |
+| `Id` | extends `string` = `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) = [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | [`_GettersTree`](../modules/pinia.md#_getterstree)<`S`\> |
+| `A` | [`_ActionsTree`](../modules/pinia.md#_actionstree) |
## Callable %{#callable}%
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `pinia?` | ``null`` \| [`Pinia`](pinia.Pinia.md) | Pinia instance to retrieve the store |
-| `hot?` | [`StoreGeneric`](../modules/pinia.md#storegeneric) | dev only hot module replacement |
+| 名称 | 类型 | 描述 |
+| :------- | :------------------------------------------------- | :----------------------------------- |
+| `pinia?` | `null` \| [`Pinia`](pinia.Pinia.md) | Pinia instance to retrieve the store |
+| `hot?` | [`StoreGeneric`](../modules/pinia.md#storegeneric) | dev only hot module replacement |
#### 返回值
• **$id**: `Id`
- store 的 id。供映射辅助函数使用。
+store 的 id。供映射辅助函数使用。
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
[pinia](../modules/pinia.md).StoreProperties
- store 的属性。
+store 的属性。
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :--- | :--------------- |
| `Id` | extends `string` |
## 层次结构 %{#hierarchy}%
store 的唯一标识符
-___
+---
### \_customProperties %{#customproperties}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
只支持开发环境。不同的 mutation 调用。
-___
+---
### storeId %{#storeid}%
#### 继承于
-[_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[storeId](pinia._SubscriptionCallbackMutationBase.md#storeid)
+[\_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[storeId](pinia._SubscriptionCallbackMutationBase.md#storeid)
-___
+---
### 类型 %{#type}%
#### 重写 %{#overrides}%
-[_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[type](pinia._SubscriptionCallbackMutationBase.md#type)
+[\_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[type](pinia._SubscriptionCallbackMutationBase.md#type)
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
仅限开发环境。在回调中所有已完成的 mutation 的数组。
-___
+---
### storeId %{#storeid}%
#### 继承于
-[_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[storeId](pinia._SubscriptionCallbackMutationBase.md#storeid)
+[\_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[storeId](pinia._SubscriptionCallbackMutationBase.md#storeid)
-___
+---
### 类型 %{#type}%
#### 重写 %{#overrides}%
-[_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[type](pinia._SubscriptionCallbackMutationBase.md#type)
+[\_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[type](pinia._SubscriptionCallbackMutationBase.md#type)
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
## 类型参数 %{#type-parameters}%
| 名称 |
-| :------ |
-| `S` |
+| :--- |
+| `S` |
## 层次结构 %{#hierarchy}%
仅限 DEV, patch 调用的数组。
-___
+---
### payload %{#payload}%
传递给 `store.$patch()` 的对象
-___
+---
### storeId %{#storeid}%
#### 继承于
-[_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[storeId](pinia._SubscriptionCallbackMutationBase.md#storeid)
+[\_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[storeId](pinia._SubscriptionCallbackMutationBase.md#storeid)
-___
+---
### 类型 %{#type}%
#### 重写 %{#overrides}%
-[_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[type](pinia._SubscriptionCallbackMutationBase.md#type)
+[\_SubscriptionCallbackMutationBase](pinia._SubscriptionCallbackMutationBase.md).[type](pinia._SubscriptionCallbackMutationBase.md#type)
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
# 接口:\_StoreOnActionListenerContext<Store, ActionName, A\> %{#interface-storeonactionlistenercontext-store-actionname-a}%
-[pinia](../modules/pinia.md)._StoreOnActionListenerContext
+[pinia](../modules/pinia.md).\_StoreOnActionListenerContext
[StoreOnActionListenerContext](../modules/pinia.md#storeonactionlistenercontext)的实际类型。
存在的目的是重构。仅供内部使用。
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `Store` | `Store` |
+| 名称 | 类型 |
+| :----------- | :--------------- |
+| `Store` | `Store` |
| `ActionName` | extends `string` |
-| `A` | `A` |
+| `A` | `A` |
## 属性
##### 参数 %{#parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :--------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `callback` | `A` extends `Record`<`ActionName`, [`_Method`](../modules/pinia.md#_method)\> ? (`resolvedReturn`: [`_Awaited`](../modules/pinia.md#_awaited)<`ReturnType`<`A`[`ActionName`]\>\>) => `void` : () => `void` |
##### 返回值
`void`
-___
+---
### args %{#args}%
传递给 action 的参数
-___
+---
### name %{#name}%
action 的名称
-___
+---
### onError %{#onerror}%
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :--------- | :----------------------------- |
| `callback` | (`error`: `unknown`) => `void` |
##### 返回值
`void`
-___
+---
### store %{#store}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
# 接口:\_StoreWithState<Id, S, G, A\> %{#interface-storewithstate-id-s-g-a}%
-[pinia](../modules/pinia.md)._StoreWithState
+[pinia](../modules/pinia.md).\_StoreWithState
具有 state 和部分功能的基础 store。不应直接使用。
## 类型参数 %{#type-parameters}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
-| `G` | `G` |
-| `A` | `A` |
+| 名称 | 类型 |
+| :--- | :--------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](../modules/pinia.md#statetree) |
+| `G` | `G` |
+| `A` | `A` |
## 层次结构 %{#hierarchy}%
[StoreProperties](pinia.StoreProperties.md).[$id](pinia.StoreProperties.md#$id)
-___
+---
### $state %{#state}%
Store 的 State。给它赋值可替换整个 state。
-___
+---
### \_customProperties %{#customproperties}%
#### 继承自
-[StoreProperties](pinia.StoreProperties.md).[_customProperties](pinia.StoreProperties.md#_customproperties)
+[StoreProperties](pinia.StoreProperties.md).[\_customProperties](pinia.StoreProperties.md#_customproperties)
## 方法 %{#methods}%
`void`
-___
+---
### $onAction %{#onaction}%
```js
store.$onAction(({ after, onError }) => {
- // 你可以在这里创建所有钩子之间的共享变量,
- // 同时设置侦听器并清理它们。
- after((resolvedValue) => {
- // 可以用来清理副作用
- // `resolvedValue` 是 action 返回的值,
- // 如果是一个 Promise,它将是已经 resolved 的值
- })
- onError((error) => {
- // 可以用于向上传递错误
- })
+ // 你可以在这里创建所有钩子之间的共享变量,
+ // 同时设置侦听器并清理它们。
+ after((resolvedValue) => {
+ // 可以用来清理副作用
+ // `resolvedValue` 是 action 返回的值,
+ // 如果是一个 Promise,它将是已经 resolved 的值
+ })
+ onError((error) => {
+ // 可以用于向上传递错误
+ })
})
```
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `callback` | [`StoreOnActionListener`](../modules/pinia.md#storeonactionlistener)<`Id`, `S`, `G`, `A`\> | callback called before every action |
-| `detached?` | `boolean` | detach the subscription from the context this is called from |
+| 名称 | 类型 | 描述 |
+| :---------- | :----------------------------------------------------------------------------------------- | :----------------------------------------------------------- |
+| `callback` | [`StoreOnActionListener`](../modules/pinia.md#storeonactionlistener)<`Id`, `S`, `G`, `A`\> | callback called before every action |
+| `detached?` | `boolean` | detach the subscription from the context this is called from |
#### 返回值
store.$onAction(({ after, onError }) => {
// 你可以在这里创建所有钩子之间的共享变量,
// 同时设置侦听器并清理它们。
- after((resolvedValue) => {
- // 可以用来清理副作用
- // `resolvedValue` 是 action 返回的值,
- // 如果是一个 Promise,它将是已解决的值
- })
- onError((error) => {
- // 可以用于向上传递错误
- })
+ after((resolvedValue) => {
+ // 可以用来清理副作用
+ // `resolvedValue` 是 action 返回的值,
+ // 如果是一个 Promise,它将是已解决的值
+ })
+ onError((error) => {
+ // 可以用于向上传递错误
+ })
})
```
移除侦听器的函数
-___
+---
### $patch %{#patch}%
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :------------- | :--------------------------------------------------------------------- | :-------------------------- |
| `partialState` | [`_DeepPartial`](../modules/pinia.md#_deeppartial)<`UnwrapRef`<`S`\>\> | patch to apply to the state |
#### 返回值
#### 类型参数 %{#type-parameters_1}%
-| 名称 | 类型 |
-| :------ | :------ |
-| `F` | extends (`state`: `UnwrapRef`<`S`\>) => `any` |
+| 名称 | 类型 |
+| :--- | :-------------------------------------------- |
+| `F` | extends (`state`: `UnwrapRef`<`S`\>) => `any` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :------------- | :----------------------------------------------------------- | :--------------------------------------------- |
| `stateMutator` | `ReturnType`<`F`\> extends `Promise`<`any`\> ? `never` : `F` | function that mutates `state`, cannot be async |
#### 返回值 {returns}
`void`
-___
+---
### $reset %{#reset}%
`void`
-___
+---
### $subscribe %{#subscribe}%
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `callback` | [`SubscriptionCallback`](../modules/pinia.md#subscriptioncallback)<`S`\> | callback passed to the watcher |
-| `options?` | { `detached?`: `boolean` } & `WatchOptions`<`boolean`\> | `watch` options + `detached` to detach the subscription from the context (usually a component) this is called from. Note that the `flush` option does not affect calls to `store.$patch()`. |
+| 名称 | 类型 | 描述 |
+| :--------- | :----------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `callback` | [`SubscriptionCallback`](../modules/pinia.md#subscriptioncallback)<`S`\> | callback passed to the watcher |
+| `options?` | { `detached?`: `boolean` } & `WatchOptions`<`boolean`\> | `watch` options + `detached` to detach the subscription from the context (usually a component) this is called from. Note that the `flush` option does not affect calls to `store.$patch()`. |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
# 接口:\_SubscriptionCallbackMutationBase %{#interface-subscriptioncallbackmutationbase}%
-[pinia](../modules/pinia.md)._SubscriptionCallbackMutationBase
+[pinia](../modules/pinia.md).\_SubscriptionCallbackMutationBase
传递给订阅回调的上下文的基本类型。内部类型。
执行 mutation 的 store 的`id`。
-___
+---
### 类型 %{#type}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :---- | :---------------------------- |
| `fn?` | (...`args`: `any`[]) => `any` |
##### 返回值
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :-------- | :------ |
| `...args` | `any`[] |
##### 返回值
`any`
-___
+---
### fakeApp %{#fakeapp}%
因为插件**必须等待 pinia 安装好后才会执行**。
默认为 false。
-___
+---
### initialState %{#initialstate}%
允许你定义每个 store 的部分初始 state。
这个 state 会在 store 创建后被应用,这样可以让你只设置测试中需要的几个属性。
-___
+---
### 插件 %{#plugins}%
在测试插件之前必装的插件。
可以向你的应用添加测试时使用的任意插件。
-___
+---
### stubActions %{#stubactions}%
注意:当提供 `createSpy()` 时,它将**只**给 `fn` 参数 传递 `undefined`。
你仍然需要在 `createSpy()` 中处理这个问题。
-___
+---
### stubPatch %{#stubpatch}%
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
Pinia 使用的应用
-___
+---
### 安装 %{#install}%
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :---- | :------------ |
| `app` | `App`<`any`\> |
##### 返回值
[Pinia](pinia.Pinia.md).[install](pinia.Pinia.md#install)
-___
+---
### state %{#state}%
▸ **use**(`plugin`): [`Pinia`](pinia.Pinia.md)
-增加了一个 store 插件来扩展每个 store
+增加了一个 store 插件来扩展每个 store
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :------- | :------------------------------------ | :------------------ |
| `plugin` | [`PiniaPlugin`](pinia.PiniaPlugin.md) | store plugin to add |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
使用 PiniaPlugin 代替
-___
+---
### StateTree %{#statetree}%
Store 的通用 state
-___
+---
### Store %{#store}%
#### 类型参数
-| 名称 | 类型 |
-| :--- | :--------------------------------------------- |
+| 名称 | 类型 |
+| :--- | :-------------------------------------------- |
| `Id` | 扩展自 `string` = `string` |
| `S` | 扩展自 [`StateTree`](pinia.md#statetree) = {} |
-| `G` | {} |
-| `A` | {} |
+| `G` | {} |
+| `A` | {} |
-___
+---
### StoreActions %{#storeactions}%
| :--- |
| `SS` |
-___
+---
### StoreGeneric %{#storegeneric}%
在访问字符串时不会失败,
这使得编写不在意传递的 store 类型的通用函数更加容易。
-___
+---
### StoreGetters %{#storegetters}%
| :--- |
| `SS` |
-___
+---
### StoreOnActionListener %{#storeonactionlistener}%
#### 类型参数
-| 名称 | 类型 |
-| :--- | :---------------------------------------- |
+| 名称 | 类型 |
+| :--- | :--------------------------------------- |
| `Id` | 扩展自 `string` |
| `S` | 扩展自 [`StateTree`](pinia.md#statetree) |
-| `G` | `G` |
-| `A` | `A` |
+| `G` | `G` |
+| `A` | `A` |
#### 类型声明 %{#type-declaration}%
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `context` | [`StoreOnActionListenerContext`](pinia.md#storeonactionlistenercontext)<`Id`, `S`, `G`, {} extends `A` ? [`_ActionsTree`](pinia.md#_actionstree) : `A`\> |
##### 返回值
`void`
-___
+---
### StoreOnActionListenerContext %{#storeonactionlistenercontext}%
#### 类型参数
-| 名称 | 类型 |
-| :--- | :---------------------------------------- |
+| 名称 | 类型 |
+| :--- | :--------------------------------------- |
| `Id` | 扩展自 `string` |
| `S` | 扩展自 [`StateTree`](pinia.md#statetree) |
-| `G` | `G` |
-| `A` | `A` |
+| `G` | `G` |
+| `A` | `A` |
-___
+---
### StoreState %{#storestate}%
| :--- |
| `SS` |
-___
+---
### SubscriptionCallback %{#subscriptioncallback}%
#### 类型参数
| 名称 |
-| :------ |
-| `S` |
+| :--- |
+| `S` |
#### 类型声明 %{#type-declaration_1}%
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :--------- | :---------------------------------------------------------------------------- |
| `mutation` | [`SubscriptionCallbackMutation`](pinia.md#subscriptioncallbackmutation)<`S`\> |
-| `state` | `UnwrapRef`<`S`\> |
+| `state` | `UnwrapRef`<`S`\> |
##### 返回值
`void`
-___
+---
### SubscriptionCallbackMutation %{#subscriptioncallbackmutation}%
| :--- |
| `S` |
-___
+---
### \_ActionsTree %{#actionstree}%
行动的对象的类型。仅供内部使用。
**仅**供内部使用
-___
+---
### \_Awaited %{#awaited}%
-Ƭ **\_Awaited**<`T`\>: `T` extends ``null`` \| `undefined` ? `T` : `T` extends `object` & { `then`: (`onfulfilled`: `F`) => `any` } ? `F` extends (`value`: infer V, ...`args`: `any`) => `any` ? [`_Awaited`](pinia.md#_awaited)<`V`\> : `never` : `T`
+Ƭ **\_Awaited**<`T`\>: `T` extends `null` \| `undefined` ? `T` : `T` extends `object` & { `then`: (`onfulfilled`: `F`) => `any` } ? `F` extends (`value`: infer V, ...`args`: `any`) => `any` ? [`_Awaited`](pinia.md#_awaited)<`V`\> : `never` : `T`
#### 类型参数
| :--- |
| `T` |
-___
+---
### \_DeepPartial %{#deeppartial}%
#### 类型参数
| 名称 |
-| :------ |
-| `T` |
+| :--- |
+| `T` |
-___
+---
### \_ExtractActionsFromSetupStore %{#extractactionsfromsetupstore}%
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
-___
+---
-### \_ExtractActionsFromSetupStore\_Keys %{#extractactionsfromsetupstore-keys}%
+### \_ExtractActionsFromSetupStore_Keys %{#extractactionsfromsetupstore-keys}%
-Ƭ **\_ExtractActionsFromSetupStore\_Keys**<`SS`\>: keyof { [K in keyof SS as SS[K] extends \_Method ? K : never]: any }
+Ƭ **\_ExtractActionsFromSetupStore_Keys**<`SS`\>: keyof { [K in keyof SS as SS[K] extends \_Method ? K : never]: any }
能够通过 IDE 进行重构的类型。
**仅**供内部使用
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
-___
+---
### \_ExtractGettersFromSetupStore %{#extractgettersfromsetupstore}%
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
-___
+---
-### \_ExtractGettersFromSetupStore\_Keys %{#extractgettersfromsetupstore-keys}%
+### \_ExtractGettersFromSetupStore_Keys %{#extractgettersfromsetupstore-keys}%
-Ƭ **\_ExtractGettersFromSetupStore\_Keys**<`SS`\>: keyof { [K in keyof SS as SS[K] extends ComputedRef ? K : never]: any }
+Ƭ **\_ExtractGettersFromSetupStore_Keys**<`SS`\>: keyof { [K in keyof SS as SS[K] extends ComputedRef ? K : never]: any }
能够通过 IDE 进行重构的类型。
**仅**供内部使用
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
-___
+---
### \_ExtractStateFromSetupStore %{#extractstatefromsetupstore}%
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
-___
+---
-### \_ExtractStateFromSetupStore\_Keys %{#extractstatefromsetupstore-keys}%
+### \_ExtractStateFromSetupStore_Keys %{#extractstatefromsetupstore-keys}%
-Ƭ **\_ExtractStateFromSetupStore\_Keys**<`SS`\>: keyof { [K in keyof SS as SS[K] extends \_Method \| ComputedRef ? never : K]: any }
+Ƭ **\_ExtractStateFromSetupStore_Keys**<`SS`\>: keyof { [K in keyof SS as SS[K] extends \_Method \| ComputedRef ? never : K]: any }
能够通过 IDE 进行重构的类型。
**仅**供内部使用
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
-___
+---
### \_GettersTree %{#getterstree}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
+| 名称 | 类型 |
+| :--- | :---------------------------------------- |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
-___
+---
### \_MapActionsObjectReturn %{#mapactionsobjectreturn}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `A` | `A` |
-| `T` | extends `Record`<`string`, keyof `A`\> |
+| 名称 | 类型 |
+| :--- | :------------------------------------- |
+| `A` | `A` |
+| `T` | extends `Record`<`string`, keyof `A`\> |
-___
+---
### \_MapActionsReturn %{#mapactionsreturn}%
#### 类型参数
| 名称 |
-| :------ |
-| `A` |
+| :--- |
+| `A` |
-___
+---
### \_MapStateObjectReturn %{#mapstateobjectreturn}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
-| `T` | extends `Record`<`string`, keyof `S` \| keyof `G` \| (`store`: [`Store`](pinia.md#store)<`Id`, `S`, `G`, `A`\>) => `any`\> = {} |
+| 名称 | 类型 |
+| :--- | :------------------------------------------------------------------------------------------------------------------------------ |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
+| `T` | extends `Record`<`string`, keyof `S` \| keyof `G` \| (`store`: [`Store`](pinia.md#store)<`Id`, `S`, `G`, `A`\>) => `any`\> = {} |
-___
+---
### \_MapStateReturn %{#mapstatereturn}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| 名称 | 类型 |
+| :----- | :------------------------------------------------------ |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
| `Keys` | extends keyof `S` \| keyof `G` = keyof `S` \| keyof `G` |
-___
+---
### \_MapWritableStateObjectReturn %{#mapwritablestateobjectreturn}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `T` | extends `Record`<`string`, keyof `S`\> |
+| 名称 | 类型 |
+| :--- | :---------------------------------------- |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `T` | extends `Record`<`string`, keyof `S`\> |
-___
+---
### \_MapWritableStateReturn %{#mapwritablestatereturn}%
#### 类型参数
-| 名称 | Type |
-| :------ | :------ |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
+| 名称 | Type |
+| :--- | :---------------------------------------- |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
-___
+---
### \_Method %{#method}%
##### 参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :-------- | :------ |
| `...args` | `any`[] |
##### 返回值
`any`
-___
+---
### \_Spread %{#spread}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `A` | extends readonly `any`[] |
+| 名称 | 类型 |
+| :--- | :----------------------- |
+| `A` | extends readonly `any`[] |
-___
+---
### \_StoreObject %{#storeobject}%
#### 类型参数
| 名称 |
-| :------ |
-| `S` |
+| :--- |
+| `S` |
-___
+---
### \_StoreWithActions %{#storewithactions}%
#### 类型参数
| 名称 |
-| :------ |
-| `A` |
+| :--- |
+| `A` |
-___
+---
### \_StoreWithGetters %{#storewithgetters}%
#### 类型参数
| 名称 |
-| :------ |
-| `G` |
+| :--- |
+| `G` |
-___
+---
### \_UnwrapAll %{#unwrapall}%
#### 类型参数
| 名称 |
-| :------ |
+| :--- |
| `SS` |
## 变量 %{#variables}%
**`param`**
- 从 'vue' 导入的 `Vue`。
+从 'vue' 导入的 `Vue`。
## 函数 %{#functions}%
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------- |
| `initialUseStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`string`, [`StateTree`](pinia.md#statetree), [`_GettersTree`](pinia.md#_getterstree)<[`StateTree`](pinia.md#statetree)\>, [`_ActionsTree`](pinia.md#_actionstree)\> | return of the defineStore to hot update |
-| `hot` | `any` | `import.meta.hot` |
+| `hot` | `any` | `import.meta.hot` |
#### 返回值
`any`
-___
+---
### createPinia %{#createpinia}%
[`Pinia`](../interfaces/pinia.Pinia.md)
-___
+---
### defineStore %{#definestore}%
#### 类型参数
-| 名称 | 类型 |
-| :--- | :--------------------------------------------- |
+| 名称 | 类型 |
+| :--- | :-------------------------------------------- |
| `Id` | 扩展自 `string` |
| `S` | 扩展自 [`StateTree`](pinia.md#statetree) = {} |
| `G` | 扩展自 `_GettersTree`<`S`\> = {} |
-| `A` | {} |
+| `A` | {} |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `id` | `Id` | id of the store (must be unique) |
-| `options` | `Omit`<[`DefineStoreOptions`](../interfaces/pinia.DefineStoreOptions.md)<`Id`, `S`, `G`, `A`\>, ``"id"``\> | options to define the store |
+| 名称 | 类型 | 描述 |
+| :-------- | :------------------------------------------------------------------------------------------------------- | :------------------------------- |
+| `id` | `Id` | id of the store (must be unique) |
+| `options` | `Omit`<[`DefineStoreOptions`](../interfaces/pinia.DefineStoreOptions.md)<`Id`, `S`, `G`, `A`\>, `"id"`\> | options to define the store |
#### 返回值
#### 类型参数
-| 名称 | 类型 |
-| :--- | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) = {} |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> = {} |
-| `A` | {} |
+| 名称 | 类型 |
+| :--- | :--------------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) = {} |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> = {} |
+| `A` | {} |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :-------- | :-------------------------------------------------------------------------------------- | :-------------------------- |
| `options` | [`DefineStoreOptions`](../interfaces/pinia.DefineStoreOptions.md)<`Id`, `S`, `G`, `A`\> | options to define the store |
#### 返回值
#### 类型参数
-| 名称 | 类型 |
-| :--- | :--------------- |
+| 名称 | 类型 |
+| :--- | :-------------- |
| `Id` | 扩展自 `string` |
-| `SS` | `SS` |
+| `SS` | `SS` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `id` | `Id` | id of the store (must be unique) |
-| `storeSetup` | () => `SS` | function that defines the store |
-| `options?` | [`DefineSetupStoreOptions`](../interfaces/pinia.DefineSetupStoreOptions.md)<`Id`, [`_ExtractStateFromSetupStore`](pinia.md#_extractstatefromsetupstore)<`SS`\>, [`_ExtractGettersFromSetupStore`](pinia.md#_extractgettersfromsetupstore)<`SS`\>, [`_ExtractActionsFromSetupStore`](pinia.md#_extractactionsfromsetupstore)<`SS`\>\> | extra options |
+| 名称 | 类型 | 描述 |
+| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------- |
+| `id` | `Id` | id of the store (must be unique) |
+| `storeSetup` | () => `SS` | function that defines the store |
+| `options?` | [`DefineSetupStoreOptions`](../interfaces/pinia.DefineSetupStoreOptions.md)<`Id`, [`_ExtractStateFromSetupStore`](pinia.md#_extractstatefromsetupstore)<`SS`\>, [`_ExtractGettersFromSetupStore`](pinia.md#_extractgettersfromsetupstore)<`SS`\>, [`_ExtractActionsFromSetupStore`](pinia.md#_extractactionsfromsetupstore)<`SS`\>\> | extra options |
#### 返回值
[`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, [`_ExtractStateFromSetupStore`](pinia.md#_extractstatefromsetupstore)<`SS`\>, [`_ExtractGettersFromSetupStore`](pinia.md#_extractgettersfromsetupstore)<`SS`\>, [`_ExtractActionsFromSetupStore`](pinia.md#_extractactionsfromsetupstore)<`SS`\>\>
-___
+---
### getActivePinia %{#getactivepinia}%
`undefined` \| [`Pinia`](../interfaces/pinia.Pinia.md)
-___
+---
### mapActions %{#mapactions}%
methods: {
// 其他方法属性
// useCounterStore 有两个 action,分别是 `increment` 与 `setCount`。
- ...mapActions(useCounterStore, { moar: 'increment', setIt: 'setCount' })
+ ...mapActions(useCounterStore, { moar: 'increment', setIt: 'setCount' }),
},
created() {
this.moar()
this.setIt(2)
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :---------- | :---------------------------------------- |
+| 名称 | 类型 |
+| :---------- | :--------------------------------------- |
| `Id` | 扩展自 `string` |
| `S` | 扩展自 [`StateTree`](pinia.md#statetree) |
| `G` | 扩展自 `_GettersTree`<`S`\> |
-| `A` | `A` |
+| `A` | `A` |
| `KeyMapper` | 扩展自 `Record`<`string`, keyof `A`\> |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keyMapper` | `KeyMapper` | object to define new names for the actions |
+| 名称 | 类型 | 描述 |
+| :---------- | :-------------------------------------------------------------------------------- | :----------------------------------------- |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keyMapper` | `KeyMapper` | object to define new names for the actions |
#### 返回值
export default {
methods: {
// 其他方法属性
- ...mapActions(useCounterStore, ['increment', 'setCount'])
+ ...mapActions(useCounterStore, ['increment', 'setCount']),
},
created() {
this.increment()
this.setCount(2) // 像往常一样传递参数
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :--- | :---------------------------------------- |
-| `Id` | 扩展自 `string` |
-| `S` | 扩展自 [`StateTree`](pinia.md#statetree) |
+| 名称 | 类型 |
+| :--- | :--------------------------------------------------- |
+| `Id` | 扩展自 `string` |
+| `S` | 扩展自 [`StateTree`](pinia.md#statetree) |
| `G` | 扩展自 [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
+| `A` | `A` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keys` | keyof `A`[] | array of action names to map |
+| 名称 | 类型 | 描述 |
+| :--------- | :-------------------------------------------------------------------------------- | :--------------------------- |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keys` | keyof `A`[] | array of action names to map |
#### 返回值
[`_MapActionsReturn`](pinia.md#_mapactionsreturn)<`A`\>
-___
+---
### mapGetters %{#mapgetters}%
// useCounterStore 有一个名为 `count` 的 state 属性以及一个名为 `double` 的 getter
...mapState(useCounterStore, {
n: 'count',
- triple: store => store.n * 3,
+ triple: (store) => store.n * 3,
// 注意如果你想要使用 `this`,那你不能使用箭头函数
custom(store) {
return this.someComponentValue + store.n
},
- doubleN: 'double'
- })
+ doubleN: 'double',
+ }),
},
created() {
this.n // 2
this.doubleN // 4
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
+| 名称 | 类型 |
+| :---------- | :------------------------------------------------------------------------------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
| `KeyMapper` | extends `Record`<`string`, keyof `S` \| keyof `G` \| (`store`: [`Store`](pinia.md#store)<`Id`, `S`, `G`, `A`\>) => `any`\> |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keyMapper` | `KeyMapper` | object of state properties or getters |
+| 名称 | 类型 | 描述 |
+| :---------- | :-------------------------------------------------------------------------------- | :------------------------------------ |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keyMapper` | `KeyMapper` | object of state properties or getters |
#### 返回值
export default {
computed: {
// 其他计算属性
- ...mapState(useCounterStore, ['count', 'double'])
+ ...mapState(useCounterStore, ['count', 'double']),
},
created() {
this.count // 2
this.double // 4
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
-| `Keys` | extends `string` \| `number` \| `symbol` |
+| 名称 | 类型 |
+| :----- | :---------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
+| `Keys` | extends `string` \| `number` \| `symbol` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keys` | readonly `Keys`[] | array of state properties or getters |
+| 名称 | 类型 | 描述 |
+| :--------- | :-------------------------------------------------------------------------------- | :----------------------------------- |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keys` | readonly `Keys`[] | array of state properties or getters |
#### 返回值
[`_MapStateReturn`](pinia.md#_mapstatereturn)<`S`, `G`, `Keys`\>
-___
+---
### mapState %{#mapstate}%
// useCounterStore 拥有一个名为 `count` 的 state 属性和一个名为 `double` 的 getter
...mapState(useCounterStore, {
n: 'count',
- triple: store => store.n * 3,
+ triple: (store) => store.n * 3,
// 如果想使用 `this`,就不能使用箭头函数
custom(store) {
return this.someComponentValue + store.n
},
- doubleN: 'double'
- })
+ doubleN: 'double',
+ }),
},
created() {
this.n // 2
this.doubleN // 4
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
+| 名称 | 类型 |
+| :---------- | :------------------------------------------------------------------------------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
| `KeyMapper` | extends `Record`<`string`, keyof `S` \| keyof `G` \| (`store`: [`Store`](pinia.md#store)<`Id`, `S`, `G`, `A`\>) => `any`\> |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keyMapper` | `KeyMapper` | object of state properties or getters |
+| 名称 | 类型 | 描述 |
+| :---------- | :-------------------------------------------------------------------------------- | :------------------------------------ |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keyMapper` | `KeyMapper` | object of state properties or getters |
#### 返回值
export default {
computed: {
// 其他计算属性
- ...mapState(useCounterStore, ['count', 'double'])
+ ...mapState(useCounterStore, ['count', 'double']),
},
created() {
this.count // 2
this.double // 4
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
-| `Keys` | extends `string` \| `number` \| `symbol` |
+| 名称 | 类型 |
+| :----- | :---------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
+| `Keys` | extends `string` \| `number` \| `symbol` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keys` | readonly `Keys`[] | array of state properties or getters |
+| 名称 | 类型 | 描述 |
+| :--------- | :-------------------------------------------------------------------------------- | :----------------------------------- |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keys` | readonly `Keys`[] | array of state properties or getters |
#### 返回值
[`_MapStateReturn`](pinia.md#_mapstatereturn)<`S`, `G`, `Keys`\>
-___
+---
### mapStores %{#mapstores}%
export default {
computed: {
// 其他计算属性
- ...mapStores(useUserStore, useCartStore)
+ ...mapStores(useUserStore, useCartStore),
},
created() {
this.userStore // id 为 "user" 的 store
this.cartStore // id 为 "cart" 的 store
- }
+ },
}
```
#### 类型参数
-| 名称 | 类型 |
-| :------- | :-------------- |
+| 名称 | 类型 |
+| :------- | :----------- |
| `Stores` | 扩展 `any`[] |
#### 参数
-| 名称 | 类型 | 描述 |
+| 名称 | 类型 | 描述 |
| :---------- | :------------ | :--------------------------------- |
| `...stores` | [...Stores[]] | list of stores to map to an object |
[`_Spread`](pinia.md#_spread)<`Stores`\>
-___
+---
### mapWritableState %{#mapwritablestate}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
-| `KeyMapper` | extends `Record`<`string`, keyof `S`\> |
+| 名称 | 类型 |
+| :---------- | :---------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
+| `KeyMapper` | extends `Record`<`string`, keyof `S`\> |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keyMapper` | `KeyMapper` | object of state properties |
+| 名称 | 类型 | 描述 |
+| :---------- | :-------------------------------------------------------------------------------- | :------------------------- |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keyMapper` | `KeyMapper` | object of state properties |
#### 返回值
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
-| `Id` | extends `string` |
-| `S` | extends [`StateTree`](pinia.md#statetree) |
-| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
-| `A` | `A` |
+| 名称 | 类型 |
+| :--- | :---------------------------------------------------- |
+| `Id` | extends `string` |
+| `S` | extends [`StateTree`](pinia.md#statetree) |
+| `G` | extends [`_GettersTree`](pinia.md#_getterstree)<`S`\> |
+| `A` | `A` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
-| `keys` | keyof `S`[] | array of state properties |
+| 名称 | 类型 | 描述 |
+| :--------- | :-------------------------------------------------------------------------------- | :------------------------ |
+| `useStore` | [`StoreDefinition`](../interfaces/pinia.StoreDefinition.md)<`Id`, `S`, `G`, `A`\> | store to map from |
+| `keys` | keyof `S`[] | array of state properties |
#### 返回值
[`_MapWritableStateReturn`](pinia.md#_mapwritablestatereturn)<`S`\>
-___
+---
### setActivePinia %{#setactivepinia}%
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :------ | :----------------------------------------------------- | :------------- |
| `pinia` | `undefined` \| [`Pinia`](../interfaces/pinia.Pinia.md) | Pinia instance |
#### 返回值
`undefined` \| [`Pinia`](../interfaces/pinia.Pinia.md)
-___
+---
### setMapStoreSuffix %{#setmapstoresuffix}%
#### 参数 %{#parameters}%
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :------- | :------- | :--------- |
| `suffix` | `string` | new suffix |
#### 返回值
`void`
-___
+---
### skipHydrate %{#skiphydrate}%
#### 类型参数
| 名称 | 类型 |
-| :------ | :------ |
-| `T` | `any` |
+| :--- | :---- |
+| `T` | `any` |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
-| `obj` | `T` | target object |
+| 名称 | 类型 | 描述 |
+| :---- | :--- | :------------ |
+| `obj` | `T` | target object |
#### 返回值
obj
-___
+---
### storeToRefs %{#storetorefs}%
#### 类型参数
-| 名称 | 类型 |
-| :------ | :------ |
+| 名称 | 类型 |
+| :--- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SS` | extends [`_StoreWithState`](../interfaces/pinia._StoreWithState.md)<`string`, [`StateTree`](pinia.md#statetree), [`_GettersTree`](pinia.md#_getterstree)<[`StateTree`](pinia.md#statetree)\>, [`_ActionsTree`](pinia.md#_actionstree), `SS`\> & [`StateTree`](pinia.md#statetree) & [`_StoreWithGetters`](pinia.md#_storewithgetters)<[`_GettersTree`](pinia.md#_getterstree)<[`StateTree`](pinia.md#statetree)\>\> & [`PiniaCustomProperties`](../interfaces/pinia.PiniaCustomProperties.md)<`string`, [`StateTree`](pinia.md#statetree), [`_GettersTree`](pinia.md#_getterstree)<[`StateTree`](pinia.md#statetree)\>, [`_ActionsTree`](pinia.md#_actionstree), `SS`\> & [`PiniaCustomStateProperties`](../interfaces/pinia.PiniaCustomStateProperties.md)<[`StateTree`](pinia.md#statetree), `SS`\> |
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :--- | :------ |
+| 名称 | 类型 | 描述 |
+| :------ | :--- | :----------------------------- |
| `store` | `SS` | store to extract the refs from |
#### 返回值
-`ToRefs`<[`StoreState`](pinia.md#storestate)<`SS`\> & [`StoreGetters`](pinia.md#storegetters)<`SS`\> & [`PiniaCustomStateProperties`](../interfaces/pinia.PiniaCustomStateProperties.md)<[`StoreState`](pinia.md#storestate)<`SS`\>\>\>
\ No newline at end of file
+`ToRefs`<[`StoreState`](pinia.md#storestate)<`SS`\> & [`StoreGetters`](pinia.md#storegetters)<`SS`\> & [`PiniaCustomStateProperties`](../interfaces/pinia.PiniaCustomStateProperties.md)<[`StoreState`](pinia.md#storestate)<`SS`\>\>\>
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
#### 参数
-| Name | Type |
-| :------ | :------ |
-| `this` | `void` |
+| Name | Type |
+| :-------------- | :----------------------------------------------------------- |
+| `this` | `void` |
| `inlineOptions` | [`ModuleOptions`](../interfaces/pinia_nuxt.ModuleOptions.md) |
-| `nuxt` | `Nuxt` |
+| `nuxt` | `Nuxt` |
#### 返回值
---
-sidebar: "auto"
+sidebar: 'auto'
editLinks: false
sidebarDepth: 3
---
#### 参数
-| 名称 | 类型 | 描述 |
-| :------ | :------ | :------ |
+| 名称 | 类型 | 描述 |
+| :-------- | :---------------------------------------------------------------- | :------------------------ |
| `options` | [`TestingOptions`](../interfaces/pinia_testing.TestingOptions.md) | 配置 pinia 测试实例的选项 |
#### 返回值
组合式 store 是可以相互使用,Pinia 当然也支持它。但有一个规则需要遵循:
-如果**两个或更多的 store 相互使用**,它们不可以通过 *getters* 或 *actions* 创建一个无限循环。它们也不可以**同时**在它们的 setup 函数中直接互相读取对方的 state:
+如果**两个或更多的 store 相互使用**,它们不可以通过 _getters_ 或 _actions_ 创建一个无限循环。它们也不可以**同时**在它们的 setup 函数中直接互相读取对方的 state:
```js
const useX = defineStore('x', () => {
## 嵌套 store %{#nested-stores}%
-注意,如果一个 store 使用另一个 store,你可以直接导入并在 *actions* 和 *getters* 中调用 `useStore()` 函数。然后你就可以像在 Vue 组件中那样使用 store。参考[共享 Getter](#shared-getters) 和[共享 Action](#shared-actions)。
+注意,如果一个 store 使用另一个 store,你可以直接导入并在 _actions_ 和 _getters_ 中调用 `useStore()` 函数。然后你就可以像在 Vue 组件中那样使用 store。参考[共享 Getter](#shared-getters) 和[共享 Action](#shared-actions)。
-对于 *setup store* ,你直接使用 store 函数**顶部**的一个 store:
+对于 _setup store_ ,你直接使用 store 函数**顶部**的一个 store:
```ts
import { useUserStore } from './user'
## 共享 Getter %{#shared-getters}%
-你可以直接在一个 *getter* 中调用 `useOtherStore()`:
+你可以直接在一个 _getter_ 中调用 `useOtherStore()`:
```js
import { defineStore } from 'pinia'
## 共享 Actions %{#shared-actions}%
-*actions* 也一样:
+_actions_ 也一样:
```js
import { defineStore } from 'pinia'
- `createStore()` 变成 `defineStore()`
- 在订阅中,`storeName` 变成 `storeId`
- `PiniaPlugin` 更名为 `PiniaVuePlugin`(Vue 2 的 Pinia 插件)
-- `$subscribe()` 不再接受 *boolean* 作为第二个参数,而是传递一个带有 `detached: true` 的对象。
+- `$subscribe()` 不再接受 _boolean_ 作为第二个参数,而是传递一个带有 `detached: true` 的对象。
- Pinia 插件不再直接接收 store 的 `id`。使用 `store.$id` 代替。
## 非兼容性更新 %{#breaking-changes}%
这是构建文件为支持 Node.js 中的原生 ESM 模块进行的现代化适配。为更好地支持 Node,文件现在使用的扩展名是 `.mjs` 和 `.cjs`。要解决这个问题,你有两种可用的方法:
- 如果你使用 Vue CLI 4.x,升级你的依赖。具体修复步骤如下。
+
- 如果你不可能升级,请将下面的代码添加到你的 `vue.config.js` 中:
```js
Vuex 有一个概念,带有多个模块的单一 store。这些模块可以被命名,甚至可以互相嵌套。
-将这个概念过渡到 Pinia 最简单的方法是,你以前使用的每个模块现在都是一个 *store*。每个 store 都需要一个 `id`,类似于 Vuex 中的命名空间。这意味着每个 store 都有命名空间的设计。嵌套模块也可以成为自己的 store。互相依赖的 store 可以直接导入其他 store。
+将这个概念过渡到 Pinia 最简单的方法是,你以前使用的每个模块现在都是一个 _store_。每个 store 都需要一个 `id`,类似于 Vuex 中的命名空间。这意味着每个 store 都有命名空间的设计。嵌套模块也可以成为自己的 store。互相依赖的 store 可以直接导入其他 store。
你的 Vuex 模块如何重构为 Pinia store,完全取决于你,不过这里有一个示例:
state: {
firstName: '',
lastName: '',
- userId: null
+ userId: null,
},
getters: {
firstName: (state) => state.firstName,
// 读取另一个名为 `auth` 模块的 state
...rootState.auth.preferences,
// 读取嵌套于 `auth` 模块的 `email` 模块的 getter
- ...rootGetters['auth/email'].details
+ ...rootGetters['auth/email'].details,
}
- }
+ },
},
actions: {
- async loadUser ({ state, commit }, id: number) {
+ async loadUser({ state, commit }, id: number) {
if (state.userId !== null) throw new Error('Already logged in')
const res = await api.user.load(id)
commit('updateUser', res)
- }
+ },
},
mutations: {
- updateUser (state, payload) {
+ updateUser(state, payload) {
state.firstName = payload.firstName
state.lastName = payload.lastName
state.userId = payload.userId
},
- clearUser (state) {
+ clearUser(state) {
state.firstName = ''
state.lastName = ''
state.userId = null
- }
- }
+ },
+ },
}
export default storeModule
state: (): State => ({
firstName: '',
lastName: '',
- userId: null
+ userId: null,
}),
getters: {
// 不在需要 firstName getter,移除
fullName: (state) => `${state.firstName} ${state.lastName}`,
loggedIn: (state) => state.userId !== null,
// 由于使用了 `this`,必须定义一个返回类型
- fullUserDetails (state): FullUserDetails {
+ fullUserDetails(state): FullUserDetails {
// 导入其他 store
const authPreferencesStore = useAuthPreferencesStore()
const authEmailStore = useAuthEmailStore()
// `this` 上的其他 getter
fullName: this.fullName,
...authPreferencesStore.$state,
- ...authEmailStore.details
+ ...authEmailStore.details,
}
// 如果其他模块仍在 Vuex 中,可替代为
// ...vuexStore.state.auth.preferences,
// ...vuexStore.getters['auth/email'].details
// }
- }
+ },
},
actions: {
//没有作为第一个参数的上下文,用 `this` 代替
- async loadUser (id: number) {
+ async loadUser(id: number) {
if (this.userId !== null) throw new Error('Already logged in')
const res = await api.user.load(id)
this.updateUser(res)
},
// mutation 现在可以成为 action 了,不再用 `state` 作为第一个参数,而是用 `this`。
- updateUser (payload) {
+ updateUser(payload) {
this.firstName = payload.firstName
this.lastName = payload.lastName
this.userId = payload.userId
},
// 使用 `$reset` 可以轻松重置 state
- clearUser () {
+ clearUser() {
this.$reset()
- }
- }
+ },
+ },
})
```
1. 为 store 添加一个必要的 `id`,你可以让它与之前的命名保持相同。
2. 如果 `state` 不是一个函数的话 将它转换为一个函数。
3. 转换 `getters`
- 1. 删除任何返回同名 state 的 getters (例如: `firstName: (state) => state.firstName`),这些都不是必需的,因为你可以直接从 store 实例中访问任何状态。
- 2. 如果你需要访问其他的 getter,可通过 `this` 访问它们,而不是第二个参数。记住,如果你使用 `this`,而且你不得不使用一个普通函数,而不是一个箭头函数,那么由于 TS 的限制,你需要指定一个返回类型,更多细节请阅读[这篇文档](../core-concepts/getters.md#accessing-other-getters)
- 3. 如果使用 `rootState` 或 `rootGetters` 参数,可以直接导入其他 store 来替代它们,或者如果它们仍然存在于 Vuex ,则直接从 Vuex 中访问它们。
+ 1. 删除任何返回同名 state 的 getters (例如: `firstName: (state) => state.firstName`),这些都不是必需的,因为你可以直接从 store 实例中访问任何状态。
+ 2. 如果你需要访问其他的 getter,可通过 `this` 访问它们,而不是第二个参数。记住,如果你使用 `this`,而且你不得不使用一个普通函数,而不是一个箭头函数,那么由于 TS 的限制,你需要指定一个返回类型,更多细节请阅读[这篇文档](../core-concepts/getters.md#accessing-other-getters)
+ 3. 如果使用 `rootState` 或 `rootGetters` 参数,可以直接导入其他 store 来替代它们,或者如果它们仍然存在于 Vuex ,则直接从 Vuex 中访问它们。
4. 转换 `actions`
- 1. 从每个 action 中删除第一个 `context` 参数。所有的东西都应该直接从 `this` 中访问。
- 2. 如果使用其他 store,要么直接导入,要么与 getters 一样,在 Vuex 上访问。
+ 1. 从每个 action 中删除第一个 `context` 参数。所有的东西都应该直接从 `this` 中访问。
+ 2. 如果使用其他 store,要么直接导入,要么与 getters 一样,在 Vuex 上访问。
5. 转换 `mutations`
- 1. Mutation 已经被弃用了。它们可以被转换为 `action`,或者你可以在你的组件中直接赋值给 store (例如:`userStore.firstName = 'First'`)
- 2. 如果你想将它转换为 action,删除第一个 `state` 参数,用 `this` 代替任何赋值操作中的 `state`。
- 3. 一个常见的 mutation 是将 state 重置为初始 state。而这就是 store 的 `$reset` 方法的内置功能。注意,这个功能只存在于 option stores。
+ 1. Mutation 已经被弃用了。它们可以被转换为 `action`,或者你可以在你的组件中直接赋值给 store (例如:`userStore.firstName = 'First'`)
+ 2. 如果你想将它转换为 action,删除第一个 `state` 参数,用 `this` 代替任何赋值操作中的 `state`。
+ 3. 一个常见的 mutation 是将 state 重置为初始 state。而这就是 store 的 `$reset` 方法的内置功能。注意,这个功能只存在于 option stores。
正如你所看到的,你的大部分代码都可以被重复使用。如果有什么遗漏,类型安全也应该可以帮助你确定需要修改的地方。
import { useStore } from 'vuex'
export default defineComponent({
- setup () {
+ setup() {
const store = useStore()
const firstName = computed(() => store.state.auth.user.firstName)
return {
firstName,
- fullName
+ fullName,
}
- }
+ },
})
```
import { useAuthUserStore } from '@/stores/auth-user'
export default defineComponent({
- setup () {
+ setup() {
const authUserStore = useAuthUserStore()
const firstName = computed(() => authUserStore.firstName)
// 你也可以在你的组件中通过返回 store 来访问整个 store
authUserStore,
firstName,
- fullName
+ fullName,
}
- }
+ },
})
```
computed: {
// 注意,我们不是在传递一个数组,而是一个接一个的 store。
// 可以 id+'Store' 的形式访问每个 store 。
- ...mapStores(useCartStore, useUserStore)
+ ...mapStores(useCartStore, useUserStore),
},
methods: {
### 初始 State %{#initial-state}%
-在创建测试 Pinia 时,你可以通过传递一个 `initialState` 对象来设置**所有 store 的初始状态**。这个对象将被 pinia 的测试实例用于创建 store 时 *patch* store。比方说,你想初始化这个 store 的状态:
+在创建测试 Pinia 时,你可以通过传递一个 `initialState` 对象来设置**所有 store 的初始状态**。这个对象将被 pinia 的测试实例用于创建 store 时 _patch_ store。比方说,你想初始化这个 store 的状态:
```ts
import { defineStore } from 'pinia'
})
```
-由于 store 的名字是 *"counter"*,所以你需要传递相应的对象给 `initialState`:
+由于 store 的名字是 _"counter"_,所以你需要传递相应的对象给 `initialState`:
```ts
// 在测试中的某处
## 访问其他 store 的 action %{#accessing-other-stores-actions}%
-想要使用另一个 store 的话,那你直接在 *action* 中调用就好了:
+想要使用另一个 store 的话,那你直接在 _action_ 中调用就好了:
```js
import { useAuthStore } from './auth-store'
const useCounterStore = defineStore('counter', {
state: () => ({
- count: 0
+ count: 0,
}),
actions: {
increment() {
this.count++
- }
- }
+ },
+ },
})
```
unsubscribe()
```
-默认情况下,*action 订阅器*会被绑定到添加它们的组件上(如果 store 在组件的 `setup()` 内)。这意味着,当该组件被卸载时,它们将被自动删除。如果你想在组件卸载后依旧保留它们,请将 `true` 作为第二个参数传递给 *action 订阅器*,以便将其从当前组件中分离:
+默认情况下,*action 订阅器*会被绑定到添加它们的组件上(如果 store 在组件的 `setup()` 内)。这意味着,当该组件被卸载时,它们将被自动删除。如果你想在组件卸载后依旧保留它们,请将 `true` 作为第二个参数传递给 _action 订阅器_,以便将其从当前组件中分离:
```vue
<script setup>
## 向 getter 传递参数 %{#passing-arguments-to-getters}%
-*Getter* 只是幕后的**计算**属性,所以不可以向它们传递任何参数。不过,你可以从 *getter* 返回一个函数,该函数可以接受任意参数:
+_Getter_ 只是幕后的**计算**属性,所以不可以向它们传递任何参数。不过,你可以从 _getter_ 返回一个函数,该函数可以接受任意参数:
```js
export const useUserListStore = defineStore('userList', {
## 访问其他 store 的 getter %{#accessing-other-stores-getters}%
-想要使用另一个 store 的 getter 的话,那就直接在 *getter* 内使用就好:
+想要使用另一个 store 的 getter 的话,那就直接在 _getter_ 内使用就好:
```js
import { useOtherStore } from './other-store'
...mapState(useCounterStore, {
myOwnName: 'doubleCount',
// 你也可以写一个函数来获得对 store 的访问权
- double: store => store.doubleCount,
+ double: (store) => store.doubleCount,
}),
},
}
-```
\ No newline at end of file
+```
## 简介 %{#introduction}%
-Pinia 插件是一个函数,可以选择性地返回要添加到 store 的属性。它接收一个可选参数,即 *context*。
+Pinia 插件是一个函数,可以选择性地返回要添加到 store 的属性。它接收一个可选参数,即 _context_。
```js
export function myPiniaPlugin(context) {
- context.pinia // 用 `createPinia()` 创建的 pinia。
+ context.pinia // 用 `createPinia()` 创建的 pinia。
context.app // 用 `createApp()` 创建的当前应用(仅 Vue 3)。
context.store // 该插件想扩展的 store
context.options // 定义传给 `defineStore()` 的 store 的可选对象。
import { toRef, ref } from 'vue'
pinia.use(({ store }) => {
- // 为了正确地处理 SSR,我们需要确保我们没有重写任何一个
+ // 为了正确地处理 SSR,我们需要确保我们没有重写任何一个
// 现有的值
if (!Object.prototype.hasOwnProperty(store.$state, 'hasError')) {
// 在插件中定义 hasError,因此每个 store 都有各自的
```
:::tip
-还有一个可以从一个 store 类型中提取 *getter* 的 `StoreGetters` 类型。你也可以且**只可以**通过扩展 `DefineStoreOptions` 或 `DefineSetupStoreOptions` 类型来扩展 *setup store* 或 *option store* 的选项。
+还有一个可以从一个 store 类型中提取 _getter_ 的 `StoreGetters` 类型。你也可以且**只可以**通过扩展 `DefineStoreOptions` 或 `DefineSetupStoreOptions` 类型来扩展 _setup store_ 或 _option store_ 的选项。
:::
## Nuxt.js %{#nuxt-js}%
```
:::tip
-如果你使用的是 Vue 2,你在 `state` 中创建的数据与 Vue 实例中的 `data` 遵循同样的规则,即 state 对象必须是清晰的,当你想向其**添加新属性**时,你需要调用 `Vue.set()` 。**参考:[Vue#data](https://v2.cn.vuejs.org/v2/api/#data)**。
+如果你使用的是 Vue 2,你在 `state` 中创建的数据与 Vue 实例中的 `data` 遵循同样的规则,即 state 对象必须是清晰的,当你想向其**添加新属性**时,你需要调用 `Vue.set()` 。**参考:[Vue#data](https://v2.cn.vuejs.org/v2/api/#data)**。
:::
## TypeScript %{#typescript}%
你并不需要做太多努力就能使你的 state 兼容 TS。确保启用了 strict,或者至少启用了 noImplicitThis,Pinia 将自动推断您的状态类型! 但是,在某些情况下,您应该帮助它进行一些转换:
+
```ts
const useStore = defineStore('storeId', {
state: () => {
## 替换 `state` %{#replacing-the-state}%
-你**不能完全替换掉** store 的 state,因为那样会破坏其响应性。但是,你可以 *patch* 它。
+你**不能完全替换掉** store 的 state,因为那样会破坏其响应性。但是,你可以 _patch_ 它。
```js
// 这实际上并没有替换`$state`
## 订阅 state %{#subscribing-to-the-state}%
-类似于 Vuex 的 [subscribe 方法](https://vuex.vuejs.org/zh/api/index.html#subscribe),你可以通过 store 的 `$subscribe()` 方法侦听 state 及其变化。比起普通的 `watch()`,使用 `$subscribe()` 的好处是 *subscriptions* 在 *patch* 后只触发一次 (例如,当使用上面的函数版本时)。
+类似于 Vuex 的 [subscribe 方法](https://vuex.vuejs.org/zh/api/index.html#subscribe),你可以通过 store 的 `$subscribe()` 方法侦听 state 及其变化。比起普通的 `watch()`,使用 `$subscribe()` 的好处是 _subscriptions_ 在 _patch_ 后只触发一次 (例如,当使用上面的函数版本时)。
```js
cartStore.$subscribe((mutation, state) => {
})
```
-默认情况下,*state subscription* 会被绑定到添加它们的组件上 (如果 store 在组件的 `setup()` 里面)。这意味着,当该组件被卸载时,它们将被自动删除。如果你想在组件卸载后依旧保留它们,请将 `{ detached: true }` 作为第二个参数,以将 *state subscription* 从当前组件中*分离*:
+默认情况下,_state subscription_ 会被绑定到添加它们的组件上 (如果 store 在组件的 `setup()` 里面)。这意味着,当该组件被卸载时,它们将被自动删除。如果你想在组件卸载后依旧保留它们,请将 `{ detached: true }` 作为第二个参数,以将 _state subscription_ 从当前组件中*分离*:
```vue
<script setup>
// 其他配置...
// ...
// 请注意,同一个`pinia'实例
- // 可以在同一个页面的多个 Vue 应用中使用。
+ // 可以在同一个页面的多个 Vue 应用中使用。
pinia,
})
```
你将会在核心概念部分了解到更多关于每个**映射辅助函数**的信息。
-## 为什么取名 *Pinia*?%{#why-pinia}%
+## 为什么取名 _Pinia_?%{#why-pinia}%
-Pinia (发音为 `/piːnjʌ/`,类似英文中的 “peenya”) 是最接近有效包名 piña (西班牙语中的 *pineapple*,即“菠萝”) 的词。 菠萝花实际上是一组各自独立的花朵,它们结合在一起,由此形成一个多重的水果。 与 Store 类似,每一个都是独立诞生的,但最终它们都是相互联系的。 它(菠萝)也是一种原产于南美洲的美味热带水果。
+Pinia (发音为 `/piːnjʌ/`,类似英文中的 “peenya”) 是最接近有效包名 piña (西班牙语中的 _pineapple_,即“菠萝”) 的词。 菠萝花实际上是一组各自独立的花朵,它们结合在一起,由此形成一个多重的水果。 与 Store 类似,每一个都是独立诞生的,但最终它们都是相互联系的。 它(菠萝)也是一种原产于南美洲的美味热带水果。
## 更真实的示例 %{#a-more-realistic-example}%
Pinia API 与 Vuex(<=4) 也有很多不同,即:
-- *mutation* 已被弃用。它们经常被认为是**极其冗余的**。它们初衷是带来 devtools 的集成方案,但这已不再是一个问题了。
+- _mutation_ 已被弃用。它们经常被认为是**极其冗余的**。它们初衷是带来 devtools 的集成方案,但这已不再是一个问题了。
- 无需要创建自定义的复杂包装器来支持 TypeScript,一切都可标注类型,API 的设计方式是尽可能地利用 TS 类型推理。
- 无过多的魔法字符串注入,只需要导入函数并调用它们,然后享受自动补全的乐趣就好。
- 无需要动态添加 Store,它们默认都是动态的,甚至你可能都不会注意到这点。注意,你仍然可以在任何时候手动使用一个 Store 来注册它,但因为它是自动的,所以你不需要担心它。
npm install pinia @pinia/nuxt
```
-:::tip
-如果你正在使用 npm,你可能会遇到 *ERESOLVE unable to resolve dependency tree* 错误。如果那样的话,将以下内容添加到 `package.json` 中:
+:::tip
+如果你正在使用 npm,你可能会遇到 _ERESOLVE unable to resolve dependency tree_ 错误。如果那样的话,将以下内容添加到 `package.json` 中:
```js
-"overrides": {
+"overrides": {
"vue": "latest"
}
```
+
:::
-我们提供了一个 *module* 来为你处理一切,你只需要在 `nuxt.config.js` 文件的 `modules` 中添加它。
+我们提供了一个 _module_ 来为你处理一切,你只需要在 `nuxt.config.js` 文件的 `modules` 中添加它。
```js
// nuxt.config.js
npm install pinia @pinia/nuxt@0.2.1 @nuxtjs/composition-api
```
-我们提供了一个 *module* 来为你处理一切工作,你只需要在 `nuxt.config.js` 文件的 `buildModules` 中添加它。
+我们提供了一个 _module_ 来为你处理一切工作,你只需要在 `nuxt.config.js` 文件的 `buildModules` 中添加它。
```js
// nuxt.config.js