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>
相关推荐
芭拉拉小魔仙3 小时前
企业级Vue项目的状态管理:从原理到实战架构
前端·vue.js·架构
恋猫de小郭3 小时前
丰田正在使用 Flutter 开发游戏引擎 Fluorite
android·前端·flutter
闻哥4 小时前
Redis事务详解
java·数据库·spring boot·redis·缓存·面试
扶苏10024 小时前
Vue 3 响应式原理深度解析
前端·javascript·vue.js
NEXT064 小时前
React 性能优化:图片懒加载
前端·react.js·面试
PineappleCoder4 小时前
别让字体拖了后腿:FOIT/FOUT 深度解析与字体加载优化全攻略
前端·性能优化
NEXT065 小时前
后端跑路了怎么办?前端工程师用 Mock.js 自救实录
前端·后端·程序员
装不满的克莱因瓶6 小时前
Java7新特性:try-with-resources写法
java·前端·javascript·jdk·新特性·jdk7
SailingCoder7 小时前
【 从“打补丁“到“换思路“ 】一次企业级 AI Agent 的架构拐点
大数据·前端·人工智能·面试·架构·agent
~央千澈~7 小时前
抖音弹幕游戏开发之第12集:添加冷却时间机制·优雅草云桧·卓伊凡
java·服务器·前端