参考文档:https://www.cnblogs.com/chenjun1/p/11644866.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| <template> <div class="scroll-y"> <div class="mb-2">IndexDbDemo.vue</div> <button @click="addData()">增加数据</button>
<br />
<br /> <button @click="updateData()">编辑数据</button>
<br />
<br /> <button @click="deleteData()">删除数据</button>
<br /> <br /> <br /> <button @click="findData()">查找数据</button>
<div class="mt-2">显示的数据</div> <div>{{ personData }}</div> </div> </template>
<script setup>
import { reactive, toRefs } from 'vue'
const request = indexedDB.open('myDatabase') let db request.onsuccess = function (event) { db = request.result console.log('数据库打开成功') } request.onerror = function (event) { console.log('数据库打开报错') }
request.onupgradeneeded = function (event) { db = event.target.result let objectStore if (!db.objectStoreNames.contains('person')) { objectStore = db.createObjectStore('person', { keyPath: 'id' }) objectStore.createIndex('name', 'name', { unique: false }) objectStore.createIndex('email', 'email', { unique: true }) } } const addData = () => { let request = db .transaction(['person'], 'readwrite') .objectStore('person') .add({ id: 1, name: '张三', age: 24, email: 'zhangsan@example.com' })
request.onsuccess = function (event) { console.log('数据写入成功') }
request.onerror = function (event) { console.log('数据写入失败') } }
let state = reactive({ personData: {} })
const { personData } = toRefs(state)
const findData = () => { let transaction = db.transaction(['person']) let objectStore = transaction.objectStore('person') let request = objectStore.get(1)
request.onerror = function (event) { console.log('事务失败') }
request.onsuccess = function (event) { if (request.result) { state.personData = request.result console.log('Name: ' + request.result.name) console.log('Age: ' + request.result.age) console.log('Email: ' + request.result.email) } else { console.log('未获得数据记录') } } }
const updateData = () => { let request = db .transaction(['person'], 'readwrite') .objectStore('person') .put({ id: 1, name: '李四', age: 35, email: 'lisi@example.com' })
request.onsuccess = function (event) { console.log('数据更新成功') }
request.onerror = function (event) { console.log('数据更新失败') } } const deleteData = () => { let request = db.transaction(['person'], 'readwrite').objectStore('person').delete(1)
request.onsuccess = function (event) { console.log('数据删除成功') } } </script>
<style scoped lang="scss"></style>
|
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=tnjsrr6rwrrk