🚀🚀🚀 这六个事半功倍的 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 }

最后

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

往期精彩推荐

相关推荐
刺客-Andy4 分钟前
React 第五十一节 Router中useOutletContext的使用详解及注意事项
前端·javascript·react.js
NoneCoder7 分钟前
React进阶:状态管理选择题
前端·react.js·面试
巴巴_羊8 分钟前
react 生命周期
前端·react.js·前端框架
刺客-Andy8 分钟前
React 第五十二节 Router中 useResolvedPath使用详解和注意事项示例
前端·javascript·react.js
datascome10 分钟前
简数采集技巧之快速获取特殊链接网址URL方法
前端·经验分享·爬虫·程序人生·正则表达式
架构个驾驾14 分钟前
Vue2 与 Vuex 状态管理实战指南
前端·javascript·vue.js
贵州数擎科技有限公司15 分钟前
Unity 单例模式完全指南
前端
FogLetter15 分钟前
从语义化标签到JS变量:前端工程师的必修课
前端·javascript·代码规范
幸福摩天轮15 分钟前
vue2和vue3什么区别
前端
五号厂房16 分钟前
浅谈useMemo与useCallback的区别与联系
前端