🚀🚀🚀 这六个事半功倍的 Pinia 库,你一定要知道!

上次我分享了 pinia-colada,很多朋友都觉得很赞,本文将继续分享我最找到的几个非常不错的 Pinia 插件,帮助你更高效地管理应用状态。

往期精彩推荐

正文

1. pinia-plugin-persistedstate

如果你想让 localStorage / sessionStoragepinia 同步,那么可以先试试这个库,而且还支持自定义持久化方式、支持 SSR

github.com/prazdevs/pi...

下面是简单的示例:

bash 复制代码
npm install pinia-plugin-persistedstate
javascript 复制代码
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export const useStore = defineStore('main', {
  state: () => ({ someState: 'hello pinia' }),
  persist: true,
});

2. pinia-plugin-persist

如果你想在简单场景下的保持状态持久化,并且是不需要复杂配置的小项目,那么或许可以试试更加轻量的pinia-plugin-persist

bash 复制代码
npm install pinia-plugin-persist
js 复制代码
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'

const pinia = createPinia()
pinia.use(piniaPersist)

createApp({})
  .use(pinia)
  .mount('#app')

3. pinia-plugin-debounce

当你觉得频繁触发 Action,影响性能时,可以试试这个库,支持实时搜索和表单防抖!

github.com/posva/pinia...

下面是简单的示例:

bash 复制代码
npm install @pinia/plugin-debounce
javascript 复制代码
import { createPinia } from 'pinia';
import debounce from 'lodash.debounce';
import piniaPluginDebounce from '@pinia/plugin-debounce';

const pinia = createPinia();
pinia.use(piniaPluginDebounce({ debounce }));

export const useSearchStore = defineStore('search', {
  actions: {
    searchContacts() {
      // 搜索逻辑
    },
  },
  debounce: {
    searchContacts: 300, // 300ms 防抖
  },
});

4. pinia-plugin-orm

当你需要对异步数据做 ORM 映射,比如用户列表、权限模型这类复杂数据关系管理时,可以使用这个库。

github.com/codedredd/p...

下面是简单的示例:

bash 复制代码
npm install pinia-plugin-orm
ts 复制代码
// plugins/pinia-orm.ts
import { PiniaORM } from 'pinia-plugin-orm';

export default (pinia: Pinia) => {
  pinia.use(PiniaORM.install());
};
ts 复制代码
// stores/User.ts
import { defineStore } from 'pinia';
import { Model } from 'pinia-plugin-orm';

export class User extends Model {
  static entity = 'users';

  static fields() {
    return {
      id: this.attr(null),
      name: this.string(''),
      email: this.string(''),
      role: this.belongsTo(Role, 'roleId'),
    };
  }
}

export const useUserStore = defineStore('users', {
  actions: {
    async fetchUsers() {
      const data = await fetch('/api/users').then(res => res.json());
      User.insert({ data });
    },
  },
});
ts 复制代码
// stores/Role.ts
import { Model } from 'pinia-plugin-orm';

export class Role extends Model {
  static entity = 'roles';

  static fields() {
    return {
      id: this.attr(null),
      name: this.string(''),
    };
  }
}
ts 复制代码
// 在组件中使用
const users = User.query().with('role').get();

5. pinia-plugin-shared-state

允许多窗口或标签页间共享 Pinia Store 状态,通过 localStorageBroadcastChannel 同步数据。

这个是官方demo,可以在多个标签页打开:

wobsoriano.github.io/pinia-share...

github.com/wobsoriano/...

下面是简单的示例:

bash 复制代码
npm install pinia-plugin-shared-state
ts 复制代码
import { createPinia } from 'pinia';
import { createSharedState } from 'pinia-plugin-shared-state';

const pinia = createPinia();
pinia.use(createSharedState({
  enable: true,
  initialize: true,
}));

export const useAuthStore = defineStore('auth', {
  state: () => ({ user: null }),
  actions: {
    async login() {
      const response = await fetch('/api/login');
      this.user = await response.json();
    },
  },
  share: {
    enable: true,
  },
});

6. pinia-undo

Pinia Store 添加了撤销/重做功能,跟踪状态变化并提供历史记录。

github.com/wobsoriano/...

下面是简单的示例:

bash 复制代码
pnpm add pinia pinia-undo
ts 复制代码
import { PiniaUndo } from 'pinia-undo'

const pinia = createPinia()
pinia.use(PiniaUndo)

const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    count: 10,
  }),
  actions: {
    increment() {
      this.count++
    },
  },
})

const counterStore = useCounterStore()

counterStore.undo() // { count: 10 }
counterStore.redo() // { count: 10 }

counterStore.increment() // { count: 11 }
counterStore.increment() // { count: 12 }

counterStore.undo() // { count: 11 }
counterStore.undo() // { count: 10 }
counterStore.undo() // { count: 10 }

counterStore.redo() // { count: 11 }

最后

今天的分享就这些了,感谢大家的阅读,如果文章中存在错误的地方欢迎指正!

往期精彩推荐

相关推荐
中微子几秒前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_25 分钟前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
Gracemark32 分钟前
高德地图-地图选择经纬度问题【使用输入提示-使用Autocomplete进行联想输入】(复盘)
vue.js
小徐_233335 分钟前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin38 分钟前
TypeScript设计模式:适配器模式
前端·后端·node.js
遂心_1 小时前
深入理解 React Hook:useEffect 完全指南
前端·javascript·react.js
Moonbit1 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言
龙在天1 小时前
ts中的函数重载
前端
卓伊凡1 小时前
非常经典的Android开发问题-mipmap图标目录和drawable图标目录的区别和适用场景实战举例-优雅草卓伊凡
前端
前端Hardy1 小时前
HTML&CSS: 谁懂啊!用代码 “擦去”图片雾气
前端·javascript·css