场景


在上面实现一个简单的todolist之后,待办事项的数据并没有进行存储。

每次进入页面就会重新加载数据源的数据。

所以怎样将数据存储。

注:

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

参照官方的API文档,需要导入模块

import storage from '@system.storage';

读取存储的内容

storage.get(OBJECT)

参数

参数名

类型

必填

说明

key

string

内容索引。

default

string

key不存在则返回的默认值。如果未指定,则返回空字符串,长度为0。

success

Function

接口调用成功的回调函数,返回存储的内容。

fail

Function

接口调用失败的回调函数。

complete

Function

接口调用结束的回调函数。

示例

storage.get({
key: 'storage_key',
success: function(data) {
console.log('call storage.get success: ' + data);
},
fail: function(data, code) {
console.log('call storage.get fail, code: ' + code + ', data: ' + data);
},
complete: function() {
console.log('call complete');
},
});

修改存储的内容

参数

参数名

类型

必填

说明

key

string

要修改的存储内容的索引。

value

string

新值。value是长度为0的空字符串,则删除索引为key的数据项。

success

Function

接口调用成功的回调函数。

fail

Function

接口调用失败的回调函数。

complete

Function

接口调用结束的回调函数。

示例

storage.set({
key: 'storage_key',
value: 'storage value',
success: function() {
console.log('call storage.set success.');
},
fail: function(data, code) {
console.log('call storage.set fail, code: ' + code + ', data: ' + data);
},
});

通过key来进行读取和存储。

所以在上面todolist的js中导入模块后,添加生命周期方法onInit,

在初始化完成后从storage中读取数据并赋值给todolist

onInit() {
storage.get({
key: 'todoList',
success: data => {
console.log('获取Storage成功' + data);
this.todoList = JSON.parse(data)
}
});
},

然后再新建一个存储数据的方法

setStorage() {
storage.set({
key: 'todoList',
value: JSON.stringify(this.todoList)
});
},

在对todolist进行增删改时调用存储的方法

remove(index){
console.log(index)
this.todoList.splice(index,1)
this.setStorage();
},
addTodo() {
this.todoList.push({
info:this.inputTodo,
status: false
})
this.setStorage();
},
checkStatus(index){
console.log(index);
this.todoList[index].status = !this.todoList[index].status;
this.setStorage();
},

完整的js代码

import todoList from "../../common/datas/todoList.js"
import router from '@system.router';
import storage from '@system.storage';
export default {
data: {
// 待办事件列表
todoList,
inputTodo: "IDE无法调用输入"
},
onInit() {
storage.get({
key: 'todoList',
success: data => {
console.log('获取Storage成功' + data);
this.todoList = JSON.parse(data)
}
});
},
setStorage() {
storage.set({
key: 'todoList',
value: JSON.stringify(this.todoList)
});
},
computed:{
needTodoNum(){
let num = 0;
this.todoList.forEach(item => {
if(!item.status){
num++;
}
});
return num;
}
},
remove(index){
console.log(index)
this.todoList.splice(index,1)
this.setStorage();
},
addTodo() {
this.todoList.push({
info:this.inputTodo,
status: false
})
this.setStorage();
},
checkStatus(index){
console.log(index);
this.todoList[index].status = !this.todoList[index].status;
this.setStorage();
},
getNewTodo(e){
this.inputTodo = e.value;
},
goback(){
router.back();
}
}

运行效果

鸿蒙开发-使用Storage实现数据存储_接口调用