在客户端使用Lokijs存储数据
点击查看 Loki.js介绍
1.新建index.html、db.js文件;
2.index.html 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
[v-cloak]{display: none;}
/*防止{{item.body}} 闪现*/
#app{width: 400px;margin:50px auto;
background-color: #ccc;
padding:10px;box-sizing: border-box;}
li{margin:10px 0;}
button{cursor: pointer;}
</style>
</head>
<body>
<div id="app">
<ol style="">
<div>
<button @click='addData' class="addbtn">添加新数据</button>
</div>
<li v-for="item in entities"
@key="item.$loki"
v-cloak>
{{item.body}}
<button @click="removeData(item.$loki)">删除</button>
</li>
</ol>
<p v-if="!this.entities.length">还没有数据,请点击‘添加新数据’</p>
</div>
</body>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/lokijs"></script>
<script type="text/javascript" src="db.js"></script>
<script type="text/javascript">
var app = new Vue({
el:'#app',
data:{
entities:[]
},
created() { //请求数据库数据
loadCollection('notes').then(collection => {
// console.log(collection)
const _entities = collection.chain()
.find()
.simplesort('$loki', 'isdesc')
.data() //处理数据
this.entities = _entities //获取数据
console.log(this.entities)
})
},
methods:{
addData () {//添加数据
console.log('add')
loadCollection('notes').then(collection =>{
var entity = collection.insert({'body':'添加数据'})
db.saveDatabase()//保存新数据
this.entities.unshift(entity)
})
},
removeData (id) {//删除数据
console.log(id)
const _entities = this.entities.filter((entity) => {
return entity.$loki !== id
})
this.entities = _entities //删除数据
loadCollection('notes')
.then((collection) => {
collection.remove({
'$loki': id
})
db.saveDatabase() //数据库删除数据
})
}
}
})
</script>
</html>
3.db.js代码:(Lokijs配置数据库)
const db = new loki('notes', { //新建数据库集合名为 notes
autoload: true,
autoloadCallback: databaseInitialize,
autosave: true,
autosaveInterval: 3000
})
function databaseInitialize() {
const notes = db.getCollection('notes') //获取notes数据库
if (notes === null) {
db.addCollection('notes') //若notes不存在,则增加
}
}
function loadCollection(collection) { //调用数据的方法
return new Promise(resolve => {
db.loadDatabase({}, () => {
const _collection = db.getCollection(collection) || db.addCollection(collection)
resolve(_collection)
})
})
}
————————————————
版权声明:本文为CSDN博主「Fernant-Jun」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38333496/article/details/101368835
相关文章