Skip to content
| Marketplace
Sign in
Visual Studio Code>Snippets>Pinia SnippetsNew to Visual Studio Code? Get it now.
Pinia Snippets

Pinia Snippets

NicholasHsiang

|
14,001 installs
| (0) | Free
Code snippets for Pinia
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Pinia Snippets (Visual Studio Code)

用于快捷编写 Pinia。

Quickly write Pinia code.

支持在 .vue、.js、.ts、.jsx、.tsx 中触发。

Works in .vue, .js, .ts, .jsx and .tsx files.

版本要求 / Requirements

片段面向当前的 Pinia 4(要求 Vue >= 3.5.11、TypeScript >= 5.6)。不提供 Vue 2 / Pinia 2 的写法。

Snippets target the current Pinia 4 (requires Vue >= 3.5.11, TypeScript >= 5.6). Vue 2 / Pinia 2 are not covered.

相关扩展 / Also useful

  • Vue Basic Snippets,包含 Vue 2 和 3 中共用的 v-* 系列指令、import 组件、指令、服务之类的代码。 Contains code for the v-* family of directives, import components, directives, and services common to Vue 2 and 3.
  • Vue 3 Snippets,参考 Vue 3 官方文档示例及测试用例源码。ref() / computed() 等基础响应式片段在这里,本扩展只覆盖 Pinia 特有的部分。 Uses official Vue 3 examples and test cases. Reactivity primitives like ref() / computed() live there; this extension only covers Pinia-specific code.
  • JavaScript Code Snippet,参考 MDN 文档。 Using MDN documentation.
  • JavaScript Comment Snippet,参考 JSDOC、ESDOC 文档,用于便捷编写 JavaScript 注释。 Reference JSDOC, ESDOC documentation for easy writing of JavaScript comments.

Snippets

分成两类:场景片段生成一段完整可用的代码,改几个名字就能跑;API 片段是单个官方 API 的最小写法,用于查阅和补全。

Two groups: Scenarios generate a complete, working block you only need to rename a few things in; API snippets are the minimal form of each official API.

场景 / Scenarios

ds / dsa / dso / dsf / dsc / pssr 会从文件名推导 store 名和 id:在 counter.ts 中触发得到 useCounterStore 和 'counter',在 user-profile.ts 或 userProfile.ts 中都得到 useUserProfileStore 和 'user-profile'。

Store name and id are derived from the file name: counter.ts yields useCounterStore / 'counter'; both user-profile.ts and userProfile.ts yield useUserProfileStore / 'user-profile'.

prefix 场景 Scenario
pinia, cp 应用入口:创建并安装 pinia Application entry: create and install pinia
defineStore, ds 完整的 Setup Store 文件(state / getters / actions + HMR) A complete Setup Store file
defineStoreAsync, dsa 带远程请求的列表 store(loading / error / reset) A remote list store with loading and error state
defineStoreOptions, dso 完整的 Option Store 文件 A complete Option Store file
defineStoreCompose, dsc 在一个 store 里使用另一个 store Use one store inside another
defineStoreForm, dsf 表单 store:初始状态 + 提交后 $reset() Form state with $reset() after submit
useStore, us 在 <script setup> 组件中使用 store Use a store in <script setup>
useStoreOptions, uso 在 Options API 组件中使用 store Use a store from the Options API
useStoreOutside, pout 在组件外使用 store(路由守卫、拦截器) Use a store outside components
piniaPersist, pper 用 $subscribe 把单个 store 持久化到 localStorage Persist one store to localStorage
piniaPlugin, pplugin Pinia 插件:给所有 store 加持久化 A pinia plugin that persists every store
piniaOnAction, plog Pinia 插件:统一记录 action 耗时与错误 A pinia plugin that logs every action
piniaTest, ptest store 单元测试文件 A store unit test file
piniaTestComponent, ptestc 组件测试(createTestingPinia) A component test with createTestingPinia
piniaSSR, pssr SSR store(skipHydrate) An SSR store using skipHydrate

在 counter.ts 中输入 ds 得到:

Typing ds in counter.ts gives you:

import { computed, ref } from 'vue';
import { acceptHMRUpdate, defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', () => {
  // state
  const count = ref(0);

  // getters
  const double = computed(() => count.value * 2);

  // actions
  function increment(step = 1) {
    count.value += step;
  }

  // Setup Stores have no built-in $reset(), define your own
  function $reset() {
    count.value = 0;
  }

  return { count, double, increment, $reset };
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot));
}

API

prefix body description
ims import { useFeatureStore } from '@/stores/feature';
const featureStore = useFeatureStore();
Import a Pinia store and instantiate it.
imstr import { storeToRefs } from 'pinia';
const { properties } = storeToRefs(featureStore);
storeToRefs() keeps state and getters reactive when destructured.
imms import { mapState } from 'pinia';
...mapState(useFeatureStore, ['state/getter']),
Options API: map state and getters as readonly computed properties.
imma import { mapActions } from 'pinia';
...mapActions(useFeatureStore, ['action']),
Options API: map actions as methods on the component.
immws import { mapWritableState } from 'pinia';
...mapWritableState(useFeatureStore, ['state']),
Options API: map state as writable computed properties (e.g. for v-model).
imss import { mapStores } from 'pinia';
...mapStores(useFeatureStore),
Options API: map whole stores as computed properties.
ms ...mapState(useFeatureStore, ['state/getter']), Options API: map state and getters as readonly computed properties.
ma ...mapActions(useFeatureStore, ['action']), Options API: map actions as methods on the component.
mws ...mapWritableState(useFeatureStore, ['state']), Options API: map state as writable computed properties (e.g. for v-model).
mss ...mapStores(useFeatureStore), Options API: map whole stores as computed properties.
setMapStoreSuffix, smss import { setMapStoreSuffix } from 'pinia';
setMapStoreSuffix('');
Change (or remove, with an empty string) the suffix mapStores() appends.
store.$patch, sp featureStore.$patch((state) => {

});
Mutate several state properties at once. Use the function form for collections
store.$patchObject, spo featureStore.$patch({

});
Apply a partial state object. Grouped into a single devtools entry,
store.$state, sst featureStore.$state = {

};
Replace the whole state of one store (internally calls $patch()).
store.$reset, sr featureStore.$reset(); Reset state to its initial value. Built in for Option Stores only -
store.$subscribe, ss featureStore.$subscribe((mutation, state) => {

});
Watch state changes. mutation.type is 'direct' 'patch object' 'patch function'.
store.$onAction, sa const unsubscribe = featureStore.$onAction(
({ name, store, args, after, onError }) => {

after((result) => { });
onError((error) => { });
}
);
Watch actions. after() runs on success, onError() on throw or rejection.
store.$dispose, sd featureStore.$dispose(); Stop all effects and subscriptions of one store.
acceptHMRUpdate, phmr if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot));
}
Hot Module Replacement for a store (Vite). Add acceptHMRUpdate to the pinia import
setActivePinia, sap import { createPinia, setActivePinia } from 'pinia';
setActivePinia(createPinia());
Make a pinia instance active so stores can be used with no app mounted
getActivePinia, gap import { getActivePinia } from 'pinia';
const pinia = getActivePinia();
Read the currently active pinia instance. Returns undefined if none is active.
disposePinia, dp import { disposePinia } from 'pinia';
disposePinia(pinia);
Dispose an entire pinia instance: stops every store and releases its state.
skipHydrate, skh import { skipHydrate } from 'pinia';
const state = skipHydrate(ref(null));
SSR: mark state as non-hydratable so the server payload does not overwrite it
shouldHydrate, shy import { shouldHydrate } from 'pinia';
if (shouldHydrate(value)) {

}
Check whether a value is hydratable, i.e. not marked with skipHydrate().
pinia.use, pu pinia.use(({ store, options, app, pinia }) => {

});
Register a plugin. Must run before app.use(pinia).
pinia.state, pstate pinia.state.value = JSON.parse(payload); The root state of every store. Serialize it on the SSR server and assign it back
storeAction, pact export const useFeatureStore = defineStore('feature', ({ action }) => {
// wrapped so $onAction also fires when called from inside the store
const doSomething = action(async () => {

}, 'doSomething');

return { doSomething };
});
The setup function receives a { action } helper (Pinia 4).

开发 / Development

片段源文件在 src/javascript/(pinia-scenarios.json 场景、pinia-api.json 单个 API),改完跑 npm run build 生成 snippets/javascript.json(构建产物,已 gitignore,不要直接改)。npm run package 打包成 .vsix。

Snippets live in src/javascript/ (pinia-scenarios.json, pinia-api.json). Run npm run build to generate snippets/javascript.json — never edit that directly. npm run package builds a .vsix.

新增片段后记得同步上面的表格。

Remember to update the table above when adding snippets.

License 📃

MIT License

Donate

xianghongai@gmail.com

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft