欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3使用indexDB緩存靜態(tài)資源的示例代碼

 更新時(shí)間:2024年10月12日 09:40:14   作者:Lval  
IndexedDB 是一個(gè)瀏覽器內(nèi)建的數(shù)據(jù)庫(kù),它可以存放對(duì)象格式的數(shù)據(jù),默認(rèn)情況下,瀏覽器會(huì)將自身所在的硬盤位置剩余容量全部作為indexedDB的存儲(chǔ)容量,本文給大家介紹了Vue3使用indexDB緩存靜態(tài)資源,需要的朋友可以參考下

indexDB

IndexedDB 是一個(gè)瀏覽器內(nèi)建的數(shù)據(jù)庫(kù),它可以存放對(duì)象格式的數(shù)據(jù),默認(rèn)情況下,瀏覽器會(huì)將自身所在的硬盤位置剩余容量全部作為indexedDB的存儲(chǔ)容量

indexDB的使用

1.初始化數(shù)據(jù)庫(kù)

注:數(shù)據(jù)庫(kù)的相關(guān)操作都是異步的

const request = indexedDB.open(name, version)
//name:數(shù)據(jù)庫(kù)名稱,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ò)指定字段查詢記錄  
        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)需要訪問(wèn)的表,并設(shè)置讀寫權(quán)限(默認(rèn)只有讀取權(quán)限)
    const transaction = db.transaction(['test‘], 'readwrite')
    //獲取指定名稱的對(duì)象存儲(chǔ)(表)
    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表,通過(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)
	// 處理查詢結(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. 清除對(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)類型為 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)文章

最新評(píng)論