Vue使用 IndexDB vue操作IndexDB数据库 Vue操作IndexDB数据库
Vue使用 IndexDB vue操作IndexDB数据库 Vue操作IndexDB数据库
大部分场景使用 LocalStore都足够了,但是 如果要考虑大数据的话,LocalStore支持并不是很好,有内存限制,并且数据过大 LocalStore解析和存储性能不是很好,这时候可以使用 IndexDB,数据格式 是和 数据库一样,可以创建多个数据库,数据库里面有多个表
安装 IndexDB类库
原生 IndexDB操作API并不是很方便,可以使用第三方类库,可以极大的减少工作量,调用IndexDB和LocalStore API很像,我这边使用过的是 LOCALFORAGE 官网
支持存储类型有:

npm
npm install localforage
或者 使用 yrm
yarn add localforage
引入 localForage
在 main.js 中引用
import Vue from 'vue'
import App from './App'
import router from './router'
// IndexDB封装类库 https://localforage.github.io/localForage/#installation
import localforage from 'localforage'
Vue.use(localforage)
// 将 localforage 挂载到全局示例, 这样就可以在任何地方 用 this.$localforage 操作
Vue.prototype.$localforage = localforage
console.info('localforage初始化成功,使用 this.$localforage 调用')
// 创建一个 默认的 IndexDB数据库挂载到全局
const demoDataBase = localforage.createInstance({
name: 'demoDataBase'
})
Vue.prototype.$demoDataBase = demoDataBase
console.info('默认数据库 demoDataBase 初始化成功,使用 this.$demoDataBase 调用')
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
测试 新增数据、获取数据
在 demoDataBase数据库新增一条数据
// 操作 demoDataBase数据库
this.$demoDataBase.setItem('测试demoDataBase', '我是测试值').then(function (value) {
// Do other things once the value has been saved.
console.log(value)
}).catch(function (err) {
// This code runs if there were any errors
console.log(err)
})
// 不需要回调
this.$demoDataBase.setItem('测试demoDataBase2', '我是测试值2')
查看是否生效,数据已经新增上去了,一共两条

获取数据也很简单
// 操作 demoDataBase数据库
this.$demoDataBase.getItem('测试demoDataBase').then(function (value) {
// Do other things once the value has been saved.
console.log(value)
}).catch(function (err) {
// This code runs if there were any errors
console.log(err)
})
// 不需要回调
this.$demoDataBase.getItem('测试demoDataBase2')
Vue3 用法
vue3用法上有些不一样,需要使用到 async 、await,因为getItem、setItem是异步的
赋值数据
js封装
import localforage from "localforage";
const dictDataBase = {
// 初始化IndexDB数据库
dictDataDataBase: localforage.createInstance({
name: "dictDataDataBase",
}),
// 获取数据
get: async function (key) {
return await this.dictDataDataBase.getItem(key);
}
};
export default dictDataBase;
Vue组件获取数据
<script setup>
import dictDataBase from "@/utils/dictDataBase";
const statusOptions = ref([])
onBeforeMount(async () => {
await dictDataBase.get().then((v) => {
// 直接赋值,不要使用 statusOptions.value.push
statusOptions.value = v;
});
});
</script>
还有删除、查询等更多API不一一演示了,可以进入官网 查看更多
Vue与IndexDB
本文介绍如何在Vue项目中使用IndexDB进行数据存储,包括安装第三方库localForage、基本的增删查改操作及Vue3中的实现方式。
646

被折叠的 条评论
为什么被折叠?



