vue缓存用法

Store 临时缓存

特点:需要定义,有初始值、响应式、全局使用、刷新重置

Pinia官方文档 https://pinia.vuejs.org

创建 store 缓存

示例代码

复制代码
import {defineStore} from 'pinia'
import {store} from '/@/store'

export const useMyStore = defineStore({
  // 定义缓存id
  id: 'my-store',
  // 在这里写当前缓存里储存的变量
  state() {
    return {
      msg: 'hello world!!',
    }
  },
  // 定义当前缓存公开的 getters,相当于vue的计算属性
  getters: {
    getMsg(): string {
      return this.msg
    },
  },
  // 定义当前缓存公开的方法,可以直接调用并传参
  actions: {
    setMsg(msg: string) {
      this.msg = msg
    },
  },
})

// 在vue3的setup方法之外使用时,需要调用此方法
export function useUseMyStoreWithOut() {
  return useMyStore(store)
}

使用 store 缓存

示例代码

复制代码
<template>
  {{ myStore.getMsg }}
</template>

<script lang="ts">
import {useMyStore} from '/@/store/modules/myStore'

export default {
  name: '',
  setup() {
    const myStore = useMyStore()
    console.log(myStore.getMsg)

    return {
      myStore,
    }
  },
}
</script>

复制

LocalStorage 长期缓存

特点:无需定义,无初始值、非响应式、全局使用、刷新不重置、多页面可通用、可设置过期时间

调用缓存

以下为调用 LocalStorage 的示例代码

复制代码
<template>
  {{ myStoreKey }}
</template>

<script lang="ts">
import {createLocalStorage} from '/@/utils/cache'

export default {
  name: '',
  setup() {
    const ls = createLocalStorage()
    let myStoreKey = ls.get('myStoreKey')
    console.log(myStoreKey)

    function set(value) {
      ls.set('myStoreKey', value)
    }

    return {
      myStoreKey,
      set,
    }
  },
}
</script>
相关推荐
梦梦代码精4 分钟前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
刘一说10 分钟前
Vue3 组合式 API(Composition API):逻辑复用的革命性实践
vue.js·vue
seabirdssss1 小时前
《bootstrap is not defined 导致“获取配置详情失败”?一次前端踩坑实录》
前端·bootstrap·html
kgduu1 小时前
js之表单
开发语言·前端·javascript
爬山算法1 小时前
Hibernate(51)Hibernate的查询缓存如何使用?
spring·缓存·hibernate
谢尔登3 小时前
Vue3 响应式系统——computed 和 watch
前端·架构
愚公移码3 小时前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
虹科网络安全4 小时前
艾体宝新闻 | Redis 月度更新速览:2025 年 12 月
数据库·redis·缓存
欣然~5 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python
一个小废渣5 小时前
Flutter Web端网络请求跨域错误解决方法
前端·flutter