美文网首页
IndexedDB 示例

IndexedDB 示例

作者: wlianfu | 来源:发表于2021-04-27 18:14 被阅读0次
    
    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...');
    };
    

    相关文章

      网友评论

          本文标题:IndexedDB 示例

          本文链接:https://www.haomeiwen.com/subject/gejprltx.html