IndexedDB 示例

2021-04-27  本文已影响0人  wlianfu

const DB = window.indexedDB;

const userInfo = [
  { userName: 'Stone', Age: 30, cityName: '上海' },
  { userName: 'John', Age: 25, cityName: '杭州' },
  { userName: 'Mico', Age: 35, cityName: '深圳' },
];

const dbName = 'userDB';

const request = DB.open('userDB', 2);

// 创建数据库失败时触发
request.onerror = event => {
  console.log('打开数据库-userDB-失败: ', event);
};

// 创建数据库成功时触发
request.onsuccess = event => {
  const db = (event.target as any).result;

  const newUserStore = db.createObjectStore('newUserStore', {
    keyPath: 'userName',
  });

  userInfo.map(item => {
    newUserStore.add(item.userName);
  });

  db.close();

  console.log('打开数据库 done...');
};

// 创建新数据库或修改数据库版本号时触发
request.onupgradeneeded = event => {
  const db = (event.target as any).result;

  const userStore = db.createObjectStore('userStore', {
    keyPath: 'userName',
  });

  userInfo.map(item => {
    userStore.add(item.userName);
  });

  db.close();

  console.log('更新数据库 done...');
};
上一篇 下一篇

猜你喜欢

热点阅读