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>
相关推荐
foundbug9992 小时前
Modbus协议C语言实现(易于移植版本)
java·c语言·前端
Luna-player2 小时前
在前端中list.map的用法
前端·数据结构·list
用户47949283569153 小时前
面试官问 React Fiber,这一篇文章就够了
前端·javascript·react.js
LYFlied3 小时前
【一句话概述】Webpack、Vite、Rollup 核心区别
前端·webpack·node.js·rollup·vite·打包·一句话概述
用户841794814563 小时前
vxe-table 实现滚动加载数据,无限加载数据教程
vue.js
reddingtons3 小时前
PS 参考图像:线稿上色太慢?AI 3秒“喂”出精细厚涂
前端·人工智能·游戏·ui·aigc·游戏策划·游戏美术
一水鉴天3 小时前
整体设计 定稿 之23+ dashboard.html 增加三层次动态记录体系仪表盘 之2 程序 (Q199 之2) (codebuddy)
开发语言·前端·javascript
刘发财3 小时前
前端一行代码生成数千页PDF,dompdf.js新增分页功能
前端·typescript·开源
_请输入用户名3 小时前
Vue 3 源码项目结构详解
前端·vue.js
前端无涯3 小时前
Vue3---(2)setup
vue.js