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

