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>
相关推荐
zhangxingchao几秒前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒2 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic3 小时前
SwiftUI 手势笔记
前端·后端
橙子家3 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518133 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州3 小时前
CSS aspect-ratio 属性完全指南
前端
Pedantic5 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘5 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
一颗烂土豆6 小时前
Meshopt 压缩深度解析,为什么它比 Draco 更快
前端·javascript·webgl