IDBObjectStore: thuộc tính autoIncrement

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

Note: This feature is available in Web Workers.

Thuộc tính chỉ đọc autoIncrement của giao diện IDBObjectStore trả về giá trị của cờ tự động tăng cho object store này.

Lưu ý rằng mỗi object store có bộ đếm tự động tăng riêng biệt.

Giá trị

Một giá trị boolean:

Giá trị Ý nghĩa
true Object store có tự động tăng.
false Object store không tự động tăng.

Ví dụ

Trong đoạn mã sau, chúng ta mở một giao dịch read/write trên cơ sở dữ liệu và thêm một số dữ liệu vào object store bằng add(). Sau khi object store được tạo, chúng ta ghi objectStore.autoIncrement ra console. Để xem ví dụ hoạt động đầy đủ, hãy tham khảo ứng dụng To-do Notifications của chúng tôi (xem ví dụ trực tiếp).

js
// Mở cơ sở dữ liệu
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.appendChild(document.createElement("li")).textContent =
    "Database initialized.";

  // Lưu kết quả mở cơ sở dữ liệu vào biến db.
  // Biến này được sử dụng nhiều ở dưới
  db = DBOpenRequest.result;

  // Chạy hàm addData() để thêm dữ liệu vào cơ sở dữ liệu
  addData();
};

function addData() {
  // Tạo một đối tượng mới sẵn sàng chèn vào IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // mở một giao dịch db read/write, sẵn sàng để thêm dữ liệu
  const transaction = db.transaction(["toDoList"], "readwrite");

  // báo cáo về việc giao dịch hoàn tất thành công
  transaction.oncomplete = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction completed.";
  };

  transaction.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction not opened due to error. Duplicate items not allowed.";
  };

  // tạo một object store trên giao dịch
  const objectStore = transaction.objectStore("toDoList");
  console.log(objectStore.autoIncrement);

  // Gửi yêu cầu thêm đối tượng newItem vào object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // báo cáo sự thành công của yêu cầu
    note.appendChild(document.createElement("li")).textContent =
      "Request successful.";
  };
}

Đặc tả kỹ thuật

Specification
Indexed Database API 3.0
# ref-for-dom-idbobjectstore-autoincrement①

Tương thích trình duyệt

Xem thêm