树形结构数据存储在 IndexedDB

树形结构数据存储在 IndexedDB
This commit is contained in:
TimSpan 2024-09-03 10:05:40 +08:00
parent 9ddd042f93
commit 8ce9714a0a
1 changed files with 81 additions and 3 deletions

View File

@ -95,10 +95,88 @@ const cascaderChange = (value: any, selectedOptions: any): void => {
formState.administrativeDivisionCodes = [...value] formState.administrativeDivisionCodes = [...value]
} }
const dbName = 'myDatabase' //
const storeName = 'treeStore' //
// IndexedDB
const openDB = () => {
return new Promise<IDBDatabase>((resolve, reject) => {
// 'myDatabase'
const request = indexedDB.open(dbName, 1)
//
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result
// 'treeStore'
db.createObjectStore(storeName)
}
//
request.onsuccess = (event) => {
// resolve使
resolve((event.target as IDBOpenDBRequest).result)
}
//
request.onerror = (event) => {
// reject
reject((event.target as IDBOpenDBRequest).error)
}
})
}
// IndexedDB
const storeTreeData = async (data: any) => {
const db = await openDB() //
const transaction = db.transaction(storeName, 'readwrite') //
const store = transaction.objectStore(storeName) //
// 使 'treeData'
store.put(data, 'treeData')
//
transaction.oncomplete = () => {
console.log('Data stored successfully') //
}
}
// IndexedDB
const loadTreeFromCache = async (): Promise<any | null> => {
const db = await openDB() //
const transaction = db.transaction(storeName, 'readonly') //
const store = transaction.objectStore(storeName) //
// 'treeData'
const request = store.get('treeData')
//
request.onsuccess = () => {
if (request.result) {
//
options.value = request.result // options.value
}
}
}
// IndexedDB
const getTree = async () => { const getTree = async () => {
//
const cachedData = await loadTreeFromCache()
if (cachedData) {
// 使
options.value = cachedData
console.log('Loaded from cache:', cachedData)
} else {
// API
const res = await api.get<any>('/common/administrativeDivisionTree') const res = await api.get<any>('/common/administrativeDivisionTree')
console.log(res) console.log(res)
options.value = res.data options.value = res.data
// IndexedDB
await storeTreeData(res.data)
console.log('Loaded from API and stored in cache')
}
} }
import type { Rule } from 'ant-design-vue/es/form' import type { Rule } from 'ant-design-vue/es/form'
import type { FormInstance } from 'ant-design-vue' import type { FormInstance } from 'ant-design-vue'