Vue3使用indexDB緩存靜態(tài)資源的示例代碼
indexDB
IndexedDB 是一個瀏覽器內(nèi)建的數(shù)據(jù)庫,它可以存放對象格式的數(shù)據(jù),默認(rèn)情況下,瀏覽器會將自身所在的硬盤位置剩余容量全部作為indexedDB的存儲容量
indexDB的使用
1.初始化數(shù)據(jù)庫
注:數(shù)據(jù)庫的相關(guān)操作都是異步的
const request = indexedDB.open(name, version) //name:數(shù)據(jù)庫名稱,version:版本號 //數(shù)據(jù)庫在打開時, //若沒有這個庫,則會新建,默認(rèn)版本號為1; //若有,打開時的版本號比原本保存的版本號更高,則會更新這個庫,同時觸發(fā)upgradeneeded事件 //數(shù)據(jù)庫的版本號只會越來越高 //新建、編輯、刪除一個對象存儲表都會執(zhí)行更新
- success:打開成功,數(shù)據(jù)庫準(zhǔn)備就緒 ,request.result 中有了一個數(shù)據(jù)庫對象
- error:打開失敗。
- upgradeneeded:更新版本,當(dāng)數(shù)據(jù)庫的版本更新時觸發(fā),例如,1->2
let db = null; //數(shù)據(jù)庫
async function initData () {
return new Promise((resolve, reject) => {
//打開數(shù)據(jù)庫app,如果沒有app數(shù)據(jù)庫會創(chuàng)建一個
const request = window.indexedDB.open('app', 1)
request.onerror = function (event) {
console.log('數(shù)據(jù)庫打開報錯')
reject(event)
}
request.onsuccess = function (event) {
console.log('數(shù)據(jù)庫打開成功')
db = event.target.result
db.onerror = function (error) {
console.log('error---------', error)
}
resolve(db)
}
//數(shù)據(jù)庫更新
request.onupgradeneeded = function (event) {
//獲取打開(或正在升級)的數(shù)據(jù)庫對象
db = event.target.result
// 檢查數(shù)據(jù)庫中是否存在指定的對象存儲(表)
if (!db.objectStoreNames.contains('test')) {
// 如果不存在,則創(chuàng)建一個新的對象存儲 (表)
// 在對象存儲中創(chuàng)建索引,以便能夠高效地通過指定字段查詢記錄
const objectStore = db.createObjectStore('test' { keyPath: 'id', autoIncrement: true })
// 創(chuàng)建一個名為 'name' 的索引,基于 'name' 字段,允許重復(fù)值 (表頭name)
objectStore.createIndex('name', 'name', { unique: false })
// 創(chuàng)建一個名為 'blob' 的索引,基于 'blob' 字段,允許重復(fù)值(表頭blob)
objectStore.createIndex('blob', 'blob', { unique: false })
}
}
})
}
2.設(shè)置數(shù)據(jù)
async function set (data) {
return new Promise((resolve, reject) => {
//啟動需要訪問的表,并設(shè)置讀寫權(quán)限(默認(rèn)只有讀取權(quán)限)
const transaction = db.transaction(['test‘], 'readwrite')
//獲取指定名稱的對象存儲(表)
const objectStore = transaction.objectStore()
//添加數(shù)據(jù)
objectStore.add(data).onsuccess = function (event) {
resolve(event)
console.log('數(shù)據(jù)寫入成功------')
}
})
}
3.讀取數(shù)據(jù)
async function get (name) {
return new Promise((resolve, reject) => {
// l連接test表,通過index方法獲取一個索引(name)的引用,使用索引的get方法發(fā)起一個異步請求,以根據(jù)索引鍵(在這個例子中是變量name的值)檢索對象
const request = db.transaction([‘test'], 'readwrite')
.objectStore('test').index('name').get(name)
request.onsuccess = function (event) {
console.log('數(shù)據(jù)seach')
if (event.target.result) {
console.log('數(shù)據(jù)存在')
} else {
console.log('數(shù)據(jù)不存在')
}
resolve(event.target.result)
}
request.onerror = function (event) {
console.log('數(shù)據(jù)seach失敗')
reject(event)
}
})
4.刪除數(shù)據(jù)
async function del (name) {
return new Promise((resolve, reject) => {
// 獲取要刪除的數(shù)據(jù)的引用
const transaction = db.transaction(['test'], 'readwrite')
const objectStore = transaction.objectStore('test')
const index = objectStore.index('name')
const request = index.get(name)
// 處理查詢結(jié)果
request.onsuccess = function (event) {
const record = event.target.result
if (record) {
// 獲取主鍵 id
const id = record.id
// 使用主鍵 id 刪除記錄
const deleteRequest = objectStore.delete(id)
// 刪除成功
deleteRequest.onsuccess = function () {
console.log('數(shù)據(jù)刪除成功------')
resolve()
}
deleteRequest.onerror = function (event) {
console.log('數(shù)據(jù)刪除失敗')
reject(event)
}
} else {
console.log('未找到匹配的記錄')
resolve() // 或者 reject(new Error('未找到匹配的記錄'));
}
}
request.onerror = function (event) {
console.log('索引查詢失敗')
reject(event)
}
})
}
5. 清除對象存儲(表)
function clear () {
//連接對象存儲
const objectStore = db.transaction(['test'], 'readwrite').objectStore('test')
//清除對象存儲
objectStore.clear()
}
存儲靜態(tài)資源
1.將靜態(tài)資源轉(zhuǎn)為流
// 從 IndexedDB 存儲圖片轉(zhuǎn)成流
function changeBlob (path) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', path, true) // 使用傳入的路徑
xhr.responseType = 'blob' // 設(shè)置響應(yīng)類型為 blob
xhr.onload = function () {
if (xhr.status === 200) {
let a = ''
a = URL.createObjectURL(xhr.response);
resolve(xhr.response) // 成功時返回 blob
} else {
reject(new Error(`Failed to load resource: ${xhr.status}`))
}
}
xhr.onerror = function () {
reject(new Error('Network error'))
}
xhr.send()
})
}
//圖片地址轉(zhuǎn)換
const getAssetsFile = url => {
return new URL(`../assets/images/${url}`, import.meta.url).href
}
2.緩存靜態(tài)資源
import { ref, onMounted } from 'vue'
const getAssetsFileImg = getAssetsFile('composite/animation.png')
const imgSrc = ref('')
const initDB = async () => {
//初始化數(shù)據(jù)庫
await initData()
// 獲取數(shù)據(jù)的引用
const animation = await get('animation')
let blob = null
// 判斷是否有數(shù)據(jù),如果沒有數(shù)據(jù)先存入數(shù)據(jù)
if (!animation) {
//將靜態(tài)資源轉(zhuǎn)為blob
blob = await changeBlob(getAssetsFileImg)
//存入靜態(tài)資源
await set({ name: 'animation', blob })
} else {
// 如果有數(shù)據(jù),取出數(shù)據(jù)流
blob = animation.blob
}
// 將取出的數(shù)據(jù)流轉(zhuǎn)為DOMString
imgSrc.value = URL.createObjectURL(blob)
}
// 將數(shù)據(jù)綁定到頁面
<img
style="width: 100%;height: 100%;"
src="imgSrc"
>
以上就是Vue3使用indexDB緩存靜態(tài)資源的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Vue3 indexDB緩存靜態(tài)資源的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vuex存儲復(fù)雜參數(shù)(如對象數(shù)組等)刷新數(shù)據(jù)丟失的解決方法
今天小編就為大家分享一篇vuex存儲復(fù)雜參數(shù)(如對象數(shù)組等)刷新數(shù)據(jù)丟失的解決方法。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
uni-app中App與webview雙向?qū)崟r通信詳細(xì)代碼示例
在移動應(yīng)用開發(fā)中,uni-app是一個非常流行的框架,它允許開發(fā)者使用一套代碼庫構(gòu)建多端應(yīng)用,包括H5、小程序、App等,這篇文章主要給大家介紹了關(guān)于uni-app中App與webview雙向?qū)崟r通信的相關(guān)資料,需要的朋友可以參考下2024-07-07
vue點擊Dashboard不同內(nèi)容 跳轉(zhuǎn)到同一表格的實例
這篇文章主要介紹了vue點擊Dashboard不同內(nèi)容 跳轉(zhuǎn)到同一表格的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
VUE和Antv G6實現(xiàn)在線拓?fù)鋱D編輯操作
這篇文章主要介紹了VUE和Antv G6實現(xiàn)在線拓?fù)鋱D編輯操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Vue?quill-editor?編輯器使用及自定義toobar示例詳解
這篇文章主要介紹了Vue quill-editor編輯器使用及自定義toobar示例詳解,這里講解編輯器quil-editor的知識結(jié)合實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07

