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 分钟前
33.如何在 React 中使用内联样式(inline styles)?
前端·javascript·react.js·前端框架·ecmascript
CodeSheep6 分钟前
DeepSeek的最新招人标准,太讽刺了。
前端·后端·程序员
不法10 分钟前
vue 地图路线渲染
前端·vue.js·ubuntu
GISer_Jing13 分钟前
从“工具应用”到“系统重构”:AI时代前端研发的范式转移与哲学思辨
前端·人工智能·学习
我家媳妇儿萌哒哒13 分钟前
Element ui el-dialog 在一个有滚动条的页面,打开一个弹框,完了再打开一个弹框后,滚动条可以滚动,怎么限制不能滚动。
前端·vue.js·ui
星辰_mya14 分钟前
系统里的“特种部队”——缓存
缓存
得想办法娶到那个女人14 分钟前
Vite + Vue 项目打包为 Electron 桌面应用 完整指南
前端·vue.js·electron
Sailing17 分钟前
🚀🚀CLI 为什么在 2025 年突然复兴?看懂 Agent、Skill、MCP、CLI 四层架构
前端·agent·ai编程
ZC跨境爬虫21 分钟前
Apple官网复刻第二阶段day_3:(还原苹果官网iPhone顶部标准文案区块,一次编写全局复用)
前端·css·ui·html·iphone
Momo__22 分钟前
CSS :has() 选择器:让父元素"看见"子元素的状态
前端·css