imba-pinia-plugin
v1.0.10
Published
pinia plugin utils cache
Downloads
255
Readme
安装
# pnpm
pnpm i imba-pinia-plugin
使用
utGetCache,utSetCache,utClearCache函数详见下方代码 凡是utSetCache调用存储过的值,都会在初始化时读取缓存赋予初始值
// test.ts
import { createPinia, defineStore } from 'pinia'
import plugin from 'imba-pinia-plugin'
export const createPiniaStore = (app) => {
const pinia = createPinia()
pinia.use(plugin) // <-- use plugin
app.use(pinia)
testPinia()
}
interface test_DYTPE {
num: number
str: string
bool: boolean
obj: {
name: string
}
obj2: Record<string, any>
arr1: number[]
arr2: [string, number, boolean, Record<string, any>, ...any]
arr3: Array<{ name: string }>
arr4: any[]
}
export const testPinia = () => {
const useTestStore = defineStore('test', {
state: (): test_DYTPE => {
return {
num: 123456,
str: 'string',
bool: false,
obj: {
name: 'test',
},
obj2: {},
arr1: [1, 2, 3, 4],
arr2: ['', 2, true, { name: 'qwe' }],
arr3: [{ name: '111' }, { name: '222' }, { name: '333' }, { name: '444' }],
arr4: [],
}
},
actions: {
testSetCache() {
if (this.bool) return
this.bool = true
const arr1 = this.arr1
const arr2 = this.arr2
const arr3 = this.arr3
arr1.push(5)
arr2.push('last test')
arr3.push({ name: '555' })
this.arr4.push('asad')
this.obj2.qq = 'qwe'
this.utSetCache({
num: 123,
str: 'str',
bool: true,
obj: { name: 'obj test' },
arr1,
arr2,
arr3,
arr4: this.arr4,
obj2: this.obj2,
})
const v1 = this.utGetCache('num')
const v2 = this.utGetCache('str')
const v3 = this.utGetCache('bool')
const v4 = this.utGetCache('obj')
const v5 = this.utGetCache('arr1')
const v6 = this.utGetCache('arr2')
const v7 = this.utGetCache('arr3')
return v1 === 123 && v2 === 'str' && v3 === false && v4.name === 'obj test' && v5.length === 5 && v6.length === 5 && v7[4].name === '555'
},
testGetCache() {
const list: any[] = []
const keys = Object.keys(this.$state)
for (const key of keys) {
const cache = this.utGetCache(key as any)
list.push(cache)
console.log('%c [ cache ]-36', 'font-size:14px; background:#41b883; color:#ffffff;', cache)
}
return list
},
testClearCache() {
this.utClearCache()
},
},
})
const testStore = useTestStore()
const result1 = testStore.testSetCache()
console.log('%c [ result1 ]-65', 'font-size:14px; background:#41b883; color:#ffffff;', result1)
const result2 = testStore.testGetCache()
console.log('%c [ result2 ]-67', 'font-size:14px; background:#41b883; color:#ffffff;', result2)
console.log('%c [ testStore ]-72', 'font-size:14px; background:#41b883; color:#ffffff;', testStore.$state)
// setTimeout(() => {
// // eslint-disable-next-line no-alert
// window.alert('test clear')
// testStore.testClearCache()
// }, 6000)
}