前言
前端有多種本地存儲方案可供選擇,常見的有:
- Cookie:小型的文本文件,存儲少量數(shù)據
- Web Storage :包括:localStorage和sessionStorage,存儲數(shù)據有上限(5M)左右
- IndexedDB:一種高級的客戶端存儲API,存儲量大、高版本瀏覽器兼容性較好
這些本地存儲方案各有優(yōu)缺點,近期發(fā)現(xiàn)一種前端本地存儲的庫 localForage,遵循“漸進增強”或“優(yōu)雅降級”的原則,集合以上多種方式,使用異步API封裝了Web Storage、IndexedDB和WebSQL的庫,提供了簡單易用的方法來存儲和檢索數(shù)據,API 相對簡單,易于上手,下面開始正式介紹localForage用法。
localForage
localForage 是一個快速而簡單的 JavaScript 存儲庫。通過使用異步存儲(IndexedDB 或 WebSQL)和簡單的類 localStorage 的 API ,localForage 能改善 Web 應用的離線體驗。
在不支持 IndexedDB 或 WebSQL 的瀏覽器中,localForage 使用 localStorage。
github地址: https://github.com/localForage/localForage
API文檔:https://localforage.github.io/localForage/#data-api-setitem
第一種使用方法
- 安裝引入
// 通過npm安裝
npm install --save localforage
// 引入
import localforage from 'localforage'
// 或通過 bower 引入
<script src="localforage.js"></script>
- 創(chuàng)建indexedDB
const firstIndexedDB = localforage.createInstance({
name: 'myFirstIndexedDB',
// 支持config所有配置
// storeName: 'keyvaluepairs', // 僅接受字母,數(shù)字和下劃線
})
- 存值
//存儲字符串
firstIndexedDB.setItem("data1", "今天是個好日子");
//存儲對象
firstIndexedDB.setItem("data2", {a:1,b: 2});
//存儲數(shù)組對象
firstIndexedDB.setItem("data3", [{a:1,b: 2}, {a:2,b:3}, {a:3,b:4}]);
4. 取值 (由于indexedDB的存取都是異步的,建議使用 promise.then() 或 async/await 去讀值,如果 key 不存在,getItem() 將返回 null。)
//第一種方法
firstIndexedDB.getItem('data1').then(value=> {
console.log("數(shù)據data1",value);
}).catch(err => {
console.log('錯誤信息', err)
});
firstIndexedDB.getItem('data2').then(value=> {
console.log("數(shù)據data2",value);
}).catch(err => {
console.log('錯誤信息', err)
});
//第二種方法
try {
const value = await firstIndexedDB.getItem('data3');
console.log("數(shù)據3",value);
} catch (err) {
console.log('錯誤信息', err)
}
5. 刪除
//輸入key值
firstIndexedDB.removeItem('data3');
- 重置清空數(shù)據庫
firstIndexedDB.clear();
- 獲取數(shù)據庫存儲key的數(shù)量
firstIndexedDB.length().then(numberOfKeys=> {
// 輸出數(shù)據庫的大小
console.log("數(shù)據庫長度",numberOfKeys);
}).catch(function(err) {
console.log("出錯",err);
});
8. 根據key的索引獲取名稱
firstIndexedDB.key(2).then(keyName=> {
// key 名
console.log("key 名",keyName);
}).catch(function(err) {
console.log("出錯",err);
});
9. 獲取數(shù)據庫所有key值
firstIndexedDB.keys().then(function(keys) {
console.log("所有key集合",keys);
}).catch(function(err) {
console.log("出錯",err);
});
10. 迭代循環(huán)打印所有key-value值
firstIndexedDB.iterate(function(value, key, iterationNumber) {
// 此回調函數(shù)將對所有 key/value 鍵值對運行
console.log([key, value,iterationNumber]);
}).then(function() {
console.log('迭代完成');
}).catch(function(err) {
console.log("出錯",err);
});
11. 提前退出迭代循環(huán)
firstIndexedDB.iterate(function(value, key, iterationNumber) {
// 此回調函數(shù)將對所有 key/value 鍵值對運行
if (iterationNumber < 3) {
console.log([key, value, iterationNumber]);
} else {
return [key, value, iterationNumber];
}
}).then(function() {
console.log('退出迭代');
}).catch(function(err) {
console.log("出錯",err);
});
- 創(chuàng)建多實例
var secondIndexedDB = localforage.createInstance({
name: "secondIndexedDB"
});
var thirdIndexedDB = localforage.createInstance({
name: "thirdIndexedDB"
});
- 設置某個數(shù)據倉庫 key 的值
secondIndexedDB.setItem("key", "value");
thirdIndexedDB.setItem("key", "value2");
- 刪除數(shù)據庫 dropInstance
14.1 調用時,若不傳參,則刪除當前實例的數(shù)據倉庫
localforage.dropInstance().then(function() {
console.log('刪除當前實例的數(shù)據倉庫')
});
14.2 調用時,若參數(shù)是指定了 name 和 storeName 屬性的對象,會刪除指定的數(shù)據倉庫
localforage.dropInstance({
name: "thirdIndexedDB",
storeName: "keyvaluepairs"
}).then(function() {
console.log('刪除指定的數(shù)據庫下的指定數(shù)據倉庫')
});
14.3 調用時,若參數(shù)僅指定了 name 屬性的對象,將刪除指定的數(shù)據庫(及其所有數(shù)據倉庫)
localforage.dropInstance({
name: "secondIndexedDB"
}).then(function() {
console.log('刪除指定的數(shù)據庫(及其所有數(shù)據倉庫)')
});
第二種使用方法
- 選擇特定存儲引擎
默認情況下,localForage 按照以下順序選擇數(shù)據倉庫的后端驅動:
(1) IndexedDB
(2) WebSQL
(3) localStorage
如果你想強制使用特定的驅動,可以使用 setDriver(),參數(shù)為以下的某一個或多個:
(1) localforage.INDEXEDDB
(2) localforage.WEBSQL
(3) localforage.LOCALSTORAGE
強制設置 localStorage 為后端的驅動
localforage.setDriver(localforage.LOCALSTORAGE);
列出可選的驅動,以優(yōu)先級排序文章來源:http://www.zghlxwxcb.cn/news/detail-788038.html
localforage.setDriver([localforage.LOCALSTORAGE, localforage.INDEXEDDB]);
- 配置
可以通過 config() 方法設置數(shù)據庫信息??捎玫倪x項有 driver,name,storeName,version,size,和 description。
localforage.config({
driver : localforage.LOCALSTORAGE, // 使用 LOCALSTORAGE;也可以使用 setDriver()
name : 'firstIndexedDB',
version : 1.0,
size : 4980736, // 數(shù)據庫的大小,單位為字節(jié)?,F(xiàn)僅 WebSQL 可用
storeName : 'keyvaluepairs1', // 僅接受字母,數(shù)字和下劃線
description : 'some description'
});
- 存值
注意:在數(shù)據交互之前,你必須先調用 config()。即在使用 getItem(),setItem(),removeItem(),clear(),key(),keys() 或 length() 前要先調用 config()。
localforage.setItem("data1", "今天是個好日子");
5. 判斷異步驅動程序初始化過程是否已完成文章來源地址http://www.zghlxwxcb.cn/news/detail-788038.html
localforage.ready().then(()=> {
// 當 localforage 將指定驅動初始化完成時,此處代碼運行
console.log(localforage.driver()); //返回正在使用的驅動的名字 "asyncStorage"
}).catch( e=> {
console.log(e); // `No available storage method found.`
// 當沒有可用的驅動時,`ready()` 將會失敗
});
- 判斷瀏覽器是否支持driverName 返回布爾值
console.log(localforage.supports(localforage.INDEXEDDB));
到了這里,關于前端本地存儲方案-localForage-vue3中使用的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!