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>
相关推荐
小小小小宇1 小时前
前端转后端基础- 变量和类型
前端
Cobyte1 小时前
1.基于依赖追踪和触发的响应式系统的本质
前端·javascript·vue.js
主宰者2 小时前
C# CommunityToolkit.Mvvm全局事件
java·前端·c#
计算机学姐2 小时前
基于SpringBoot的咖啡店管理系统【个性化推荐+数据可视化统计+配送信息】
java·vue.js·spring boot·后端·mysql·信息可视化·tomcat
前端小咸鱼一条2 小时前
16.迭代器 和 生成器
开发语言·前端·javascript
小江的记录本3 小时前
【注解】常见 Java 注解系统性知识体系总结(附《全方位对比表》+ 思维导图)
java·前端·spring boot·后端·spring·mybatis·web
web守墓人3 小时前
【前端】记一次将ruoyi vue3 element-plus迁移到arco design vue的经历
前端·vue.js·arco design
伊步沁心3 小时前
Webpack & Vite 深度解析
前端
libokaifa3 小时前
OpenSpec + TDD:让 AI 写代码,用测试兜底
前端·ai编程
用户15815963743703 小时前
搭 AI Agent 团队踩了 18 个坑,总结出这 5 个关键步骤
前端