Vue3使用indexDB緩存靜態(tài)資源的示例代碼
更新時間:2024年10月12日 09:40:14 作者:Lval
IndexedDB 是一個瀏覽器內建的數(shù)據(jù)庫,它可以存放對象格式的數(shù)據(jù),默認情況下,瀏覽器會將自身所在的硬盤位置剩余容量全部作為indexedDB的存儲容量,本文給大家介紹了Vue3使用indexDB緩存靜態(tài)資源,需要的朋友可以參考下
indexDB
IndexedDB 是一個瀏覽器內建的數(shù)據(jù)庫,它可以存放對象格式的數(shù)據(jù),默認情況下,瀏覽器會將自身所在的硬盤位置剩余容量全部作為indexedDB的存儲容量
indexDB的使用
1.初始化數(shù)據(jù)庫
注:數(shù)據(jù)庫的相關操作都是異步的
const request = indexedDB.open(name, version) //name:數(shù)據(jù)庫名稱,version:版本號 //數(shù)據(jù)庫在打開時, //若沒有這個庫,則會新建,默認版本號為1; //若有,打開時的版本號比原本保存的版本號更高,則會更新這個庫,同時觸發(fā)upgradeneeded事件 //數(shù)據(jù)庫的版本號只會越來越高 //新建、編輯、刪除一個對象存儲表都會執(zhí)行更新
- success:打開成功,數(shù)據(jù)庫準備就緒 ,request.result 中有了一個數(shù)據(jù)庫對象
- error:打開失敗。
- upgradeneeded:更新版本,當數(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' 字段,允許重復值 (表頭name)
objectStore.createIndex('name', 'name', { unique: false })
// 創(chuàng)建一個名為 'blob' 的索引,基于 'blob' 字段,允許重復值(表頭blob)
objectStore.createIndex('blob', 'blob', { unique: false })
}
}
})
}
2.設置數(shù)據(jù)
async function set (data) {
return new Promise((resolve, reject) => {
//啟動需要訪問的表,并設置讀寫權限(默認只有讀取權限)
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)
// 處理查詢結果
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)資源轉為流
// 從 IndexedDB 存儲圖片轉成流
function changeBlob (path) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', path, true) // 使用傳入的路徑
xhr.responseType = 'blob' // 設置響應類型為 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()
})
}
//圖片地址轉換
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)資源轉為blob
blob = await changeBlob(getAssetsFileImg)
//存入靜態(tài)資源
await set({ name: 'animation', blob })
} else {
// 如果有數(shù)據(jù),取出數(shù)據(jù)流
blob = animation.blob
}
// 將取出的數(shù)據(jù)流轉為DOMString
imgSrc.value = URL.createObjectURL(blob)
}
// 將數(shù)據(jù)綁定到頁面
<img
style="width: 100%;height: 100%;"
src="imgSrc"
>
以上就是Vue3使用indexDB緩存靜態(tài)資源的示例代碼的詳細內容,更多關于Vue3 indexDB緩存靜態(tài)資源的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:
相關文章
Vue實現(xiàn)用戶自定義字段顯示數(shù)據(jù)的方法
今天小編就為大家分享一篇Vue實現(xiàn)用戶自定義字段顯示數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Vue實現(xiàn)textarea固定輸入行數(shù)與添加下劃線樣式的思路詳解
這篇文章主要介紹了使用Vue實現(xiàn)textarea固定輸入行數(shù)與添加下劃線樣式的思路詳解,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
vue2從數(shù)據(jù)變化到視圖變化發(fā)布訂閱模式詳解
這篇文章主要為大家介紹了vue2從數(shù)據(jù)變化到視圖變化發(fā)布訂閱模式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09

