使用加密缓存及vuex数据持久化

207 阅读1分钟

使用加密缓存及vuex数据持久化

// 在utils的index.ts文件中
import SecureLS from 'secure-ls'

/**
 * @description: 设置缓存压缩加密
 * @return 返回Storage处理函数集合
 */
export function useStorage(options = { encodingType: 'aes', encryptionSecret: 'yide-monitoring-system-manage' }) {
    const ls = new SecureLS(options)

    // console.log(ls)
    return {
        getItem: (key: string) => ls.get(key),
        setItem: (key: string, value: any) => ls.set(key, value),
        removeItem: (key: string) => ls.remove(key),
        removeAll: () => ls.removeAll()
    }
}
  • 使用以下方法数据默认将会通过 aes 加密压缩存储在 LocalStorage
    useStorage 支持配置对象 具体看 https://softvar.github.io/secure-ls/#docs
  • 该方法也是vuex 数据持久化的默认函数,可以指定需要加密持久化的模块
// 使用方法
import { useStorage } from '@/utils/index'

const { setItem, getItem, removeItem,removeAll } = useStorage() //options?

setItem('data', '123')

const data  = getItem('data')

console.log(data) //123