vue-local-cache

兼容 Vue2 与 Vue3 的本地缓存插件,支持前缀、自动过期、按页面(vue-router)命名空间
659
Install
npm install vue-local-cache
Latest Version:1.1.2
Vue:2 · 3
License:MIT
Last Updated:Sep 22, 2026
Links: npm
Maintainer: isgang

vue-local-cache

兼容 Vue2 / Vue3 / uni-app / 微信小程序原生 的本地缓存插件,封装 localStorage(小程序端自动切换 uni.*StorageSync / wx.*StorageSync)。 支持前缀、默认过期时间、按页面(vue-router / getCurrentPages)命名空间隔离,开箱即用。

License: MIT Vue TypeScript

特性

  • ✅ 一套代码同时兼容 Vue2 / Vue3 / uni-app / 微信小程序原生(H5、小程序、App)
  • ✅ 自动识别存储层:uni.*StorageSync(uni 环境)→ wx.*StorageSync(微信小程序原生)→ localStorage(浏览器)→ 内存 Map(SSR / 隐私模式兜底)
  • ✅ 自动识别页面路径:vue-router.currentRoute.path → getCurrentPages().route → location.pathname
  • ✅ 可配置:前缀 prefix、默认过期时间 expire、是否按页面存储 pageScope
  • ✅ 七个核心方法:set / get / remove / keys(当前页)/ keysAll(全部)/ clear(当前页)/ clearAll(整个前缀)
  • ✅ 懒过期:get / keys / keysAll 时检查并自动删除过期项,不引入定时器,无内存泄漏
  • ✅ TypeScript 编写,输出 .d.ts 类型声明
  • ✅ 提供 useCache() 组合式 API(Vue3 / Vue2.7+ setup 中使用)
  • ✅ 严格作用域:clearAll 只删本插件前缀的数据,不会误伤其他业务数据

安装

# npm
npm install vue-local-cache

# pnpm
pnpm add vue-local-cache

# yarn
yarn add vue-local-cache

vue 是 peerDependency,请确保项目已安装 Vue 2.7+ 或 Vue 3。 vue-router 为可选 peerDependency,不安装时自动降级到 getCurrentPages() 或 location.pathname。

快速开始

Vue 3

// main.ts
import { createApp } from 'vue'
import router from './router'
import App from './App.vue'
import VueLocalCache from 'vue-local-cache'

const app = createApp(App)
app.use(VueLocalCache, {
  prefix: 'mall',          // 缓存前缀,默认 'app'
  expire: 3600,            // 默认过期时间(秒),默认 null(永不过期)
  pageScope: true,         // 按页面隔离,默认 true
  router                  // 可选:传入 vue-router 实例
})
app.mount('#app')
<!-- 组件内 -->
<script setup lang="ts">
import { useCache } from 'vue-local-cache'

const cache = useCache()

cache.set('user', { id: 1, name: 'Alice' })
console.log(cache.get('user'))    // { id: 1, name: 'Alice' }

// 1 秒后过期
cache.set('token', 'xxx', 1)
setTimeout(() => cache.get('token'), 1100)   // null

// 删除
cache.remove('user')

// 清空当前页面所有缓存(不影响其他页面)
cache.clear()
// 清空整个前缀下的所有缓存(跨页面)
cache.clearAll()
</script>

Vue 2

// main.js
import Vue from 'vue'
import router from './router'
import VueLocalCache from 'vue-local-cache'

Vue.use(VueLocalCache, {
  prefix: 'mall',
  expire: 3600,
  router
})

// 组件内通过 this.$cache 访问
new Vue({
  mounted() {
    this.$cache.set('user', { id: 1 })
    this.$cache.get('user')      // { id: 1 }
    this.$cache.clear()
  }
}).$mount('#app')

Vue 2.7+ 也支持组合式 API:

import { useCache } from 'vue-local-cache'

export default {
  setup() {
    const cache = useCache()
    cache.set('user', { id: 1 })
    return { cache }
  }
}

uni-app

无需任何特殊配置,自动识别 uni 全局对象并切换到 uni.*StorageSync。

// main.js
import { createSSRApp } from 'vue'
import App from './App.vue'
import VueLocalCache from 'vue-local-cache'

export function createApp() {
  const app = createSSRApp(App)
  app.use(VueLocalCache, {
    prefix: 'mall',
    expire: 3600
    // pageScope 默认 true,自动按 getCurrentPages().route 隔离
  })
  return { app }
}
<!-- pages/home/home.vue -->
<script setup>
import { useCache } from 'vue-local-cache'
const cache = useCache()
cache.set('user', { id: 1 })
// 当前页面 route = 'pages/home/home' → 规范化为 'pages_home_home'
// 最终 storage key: mall-pages_home_home:user
</script>

支持的 uni 运行时:H5 / 微信小程序 / 支付宝小程序 / 字节小程序 / App 端。

微信小程序原生(无 Vue)

无需 Vue 环境,使用 createCache() 工厂直接创建缓存实例。自动识别 wx 全局对象并切换到 wx.*StorageSync,页面路径自动取 getCurrentPages() 栈顶 route。

// utils/cache.js
import { createCache } from 'vue-local-cache'

export const cache = createCache({
  prefix: 'mall',     // 缓存前缀,默认 'app'
  expire: 3600,       // 默认过期时间(秒),默认 null(永不过期)
  pageScope: true     // 按页面隔离,默认 true
})
// pages/home/home.js
import { cache } from '../../utils/cache'

Page({
  onLoad() {
    cache.set('user', { id: 1 })
    // 当前页面 route = 'pages/home/home' → 规范化为 'pages_home_home'
    // 最终 storage key: mall-pages_home_home:user
    console.log(cache.get('user'))   // { id: 1 }
  },
  onUnload() {
    cache.clear()   // 仅清空当前页面命名空间,不影响其他页面
  }
})

使用前需在微信开发者工具中执行「工具 → 构建 npm」。同样适用于支付宝(my)、字节(tt)、百度(swan)、快手(ks)小程序原生写法。

配置选项

选项 类型 默认值 说明
prefix string 'app' 所有缓存 key 的前缀,用于多个业务/项目隔离
expire number | null null 默认过期时间(秒);null 表示永不过期,传正数作为默认过期秒数,传 0 也永不过期
pageScope boolean true 是否按页面路径划分命名空间
router any undefined 可选 vue-router 实例,用于自动获取当前页面路径

API

set(key, value, expire?)

设置缓存。

参数 类型 必填 说明
key string ✓ 缓存键
value any ✓ 缓存值(会被 JSON.stringify)
expire number | null ✗ 本次过期时间(秒);不传用全局默认(默认 null 永不过期);传正数按秒过期;传 0 或 null 永不过期
cache.set('user', { id: 1 })              // 用全局默认(默认永不过期)
cache.set('token', 'xxx', 3600)           // 1 小时后过期
cache.set('config', { x: 1 }, 0)          // 永不过期
cache.set('config', { x: 1 }, null)       // 永不过期

get(key)

获取缓存。自动检查过期,过期返回 null 并删除该条目。

const user = cache.get('user')   // { id: 1 } 或 null

remove(key)

删除单个缓存。

cache.remove('user')

keys()

列出当前页面命名空间下所有未过期的业务 key(已剥离前缀和页面部分,只返回 set 时传入的原始 key)。

遍历过程中会顺便删除已过期的条目(懒过期清理)。

cache.set('user', 1)
cache.set('list', [1, 2])
cache.set('config', { x: 1 })
cache.keys()           // ['user', 'list', 'config']

keysAll()

列出该前缀下所有页面未过期的业务 key(跨所有页面,含 pageScope=true 和 pageScope=false 两种写入形态)。

遍历过程中会顺便删除已过期的条目。

cache.set('a', 1)            // app-home:a
// 假设其他页面写入过:
//   app-other:b、app:c
cache.keysAll()           // ['a', 'b', 'c']

clear()

清空当前页面命名空间下的所有缓存,不影响其他页面。

// 假设当前 page = '/home' → 规范化为 'home'
cache.set('a', 1)   // 写入 app-home:a
cache.clear()       // 仅删除以 app-home: 开头的条目

clearAll()

清空该前缀下所有缓存(跨所有页面,同时覆盖 pageScope=true 和 pageScope=false 两种格式)。仅删除本插件写入的条目,不会误伤其他业务数据。

cache.clearAll()
// 删除所有以 'app:' 或 'app-' 开头的条目(如 app-home:a、app-other:b、app:c)
// 保留其他库写入的条目(如 otherBiz:x、appData:y)

存储格式

Key 规则

使用三层分隔符,便于在 DevTools 中直观区分:

  • 前缀和页面之间用 -(如 app-home)

  • 多级页面路径内部用 _(如 app-user_detail)

  • 页面和 key 之间用 :(如 app-home:user)

  • pageScope: true(默认):{prefix}-{page}:{key}

    • page 中的 / 会被规范化(首尾去掉、中间替换为 _),/ 或空兜底为 index
    • 例:mall-home:user、mall-user_detail:list、mall-index:user
    • uni-app 形态:mall-pages_home_home:user
  • pageScope: false:{prefix}:{key}

    • 例:mall:user

Value 结构

存储的是 JSON 字符串:

{
  "value": <原始 value>,
  "expiry": 1697245200000   // 过期时间戳(毫秒),null 表示永不过期
}

环境识别优先级

存储层(safeStorage)

  1. 小程序环境:按优先级检测全局对象 uni → wx → my → tt → swan → ks,存在 setStorageSync/getStorageSync 即用对应平台 API 适配(uni 优先,保证 uni-app 编译到小程序端时多端行为一致)
  2. 浏览器:localStorage 可写 → 原生 localStorage
  3. 兜底:内存 Map(SSR / 隐私模式 / 配额满)

页面路径(createPathGetter)

  1. vue-router(若 options.router 传入):
    • Vue3:router.currentRoute.value.path
    • Vue2:router.currentRoute.path
  2. uni-app:getCurrentPages() 栈顶页的 route(自动补 / 前缀)
  3. 浏览器:location.pathname
  4. 兜底:'/'

过期策略

采用懒过期:仅在 get(key) 时检查 expiry,过期则立即删除并返回 null。

默认永不过期:全局 expire 默认 null,未传 expire 选项时所有缓存永不过期,只有 set 时显式传入秒数或全局配置 expire 为正数才会过期。

不引入定时器或后台任务,避免:

  • SSR 多实例泄漏
  • 小程序后台被限制执行
  • 多 tab 数据竞争

如需主动清理过期项,可在路由切换或 onShow 钩子中调用 clear()。

uni-app 注意事项

  1. 存储上限:微信小程序单 key 上限 1MB,总容量 10MB;超出会触发 setStorageSync 失败(被静默忽略,不会抛错)。
  2. clearAll 作用域:严格按本插件 prefix: 前缀过滤删除,不会调用 uni.clearStorageSync()(那会清空全部业务数据)。
  3. 页面标识:使用 getCurrentPages() 栈顶 route,建议在 onShow / onLoad 时操作缓存以确保页面栈已建立。
  4. 多端一致:H5 端运行 uni-app 时 uni 全局对象也存在,存储与小程序端行为一致。

本地开发

# 安装依赖
npm install

# 构建产物(类型检查 + Vite 库模式)
npm run build
# 产出:dist/index.js (ESM) / dist/index.cjs (CJS) / dist/index.d.ts

# 运行测试(vitest + jsdom)
npm test

# 仅类型检查
npm run typecheck

手动验证

  • Vue3 示例:浏览器打开 examples/vue3.html(需先 npm run build)
  • Vue2 示例:浏览器打开 examples/vue2.html
  • DevTools:Application → Local Storage 查看 key 形态(如 mall-home:user)

项目结构

vue-local-cache/
├── src/
│   ├── index.ts        # 入口:install + useCache + 默认导出
│   ├── cache.ts        # CacheManager 缓存核心类(不依赖 Vue)
│   ├── types.ts        # CacheOptions / Cache 类型
│   ├── utils.ts        # CacheStorage 接口 + UniStorage + safeStorage + 工具
│   └── env.ts          # createPathGetter:vue-router / getCurrentPages / location 兼容
├── tests/
│   ├── cache.test.ts   # 缓存核心测试
│   ├── uni.test.ts     # uni 环境测试
│   └── wx.test.ts      # 微信小程序原生环境测试
├── examples/
│   ├── vue2.html       # Vue2 手动验证
│   └── vue3.html       # Vue3 手动验证
├── dist/               # 构建产物
├── package.json
├── vite.config.ts
└── tsconfig.json

License

MIT

Related Packages

vue-reactivestorage

Reactive layer for interacting with localStorage from Vue.

1,283 126
vue-2-crumbs

Breadcrumbs plugin for Vue.js 2 framework that allows to select parent route in...

3,891 35
@morgul/snowpack-plugin-vue2

A snowpack vue2 compiler based on `@snowpack/plugin-vue`.

9,507 6
vue-router-middleware-plugin

A vue.js plugin to implement a middleware pipeline between your routes.

4,012 11
vue2-dnd

Drag n' Drop plugin for Vue.js

2,111 12

Version History

Version Released Vue License
1.1.2 ^2.7.0 || ^3.0.0 MIT
1.1.1 ^2.7.0 || ^3.0.0 MIT
1.1.0 ^2.7.0 || ^3.0.0 MIT
1.0.4 ^2.7.0 || ^3.0.0 MIT
1.0.3 ^2.7.0 || ^3.0.0 MIT