当前位置: 首页 > news >正文

【HarmonyOS】API6使用storage实现轻量级数据存储

 写在前面

本篇内容基于API6 JS语言进行开发,通过结合轻量级数据存储开发指导的文档,帮助大家完成一个实际的代码案例,通过这个小案例,可以实现简单数据的存储。

参考文档:文档中心

1、页面布局

首先我们编写一个简单的页面布局,页面中只有一个文本和两个按钮,文本用来展示存储的数据结果,按钮用来控制存储和获取数据,代码如下:

<div class="container"><text>{{content}}</text><div class="option"><button class="button" value="存储" "onclickSave"></button><button class="button" value="获取" "onclickGet"></button></div>
</div>

2、页面样式

然后我们简单处理一下页面的样式,代码如下:

.container {flex-direction: column;justify-content: center;align-items: center;margin-top: 20px;
}
.option {flex-direction: row;justify-content: center;align-items: center;margin-top: 20px;margin-right: 20px;
}
.button {font-size: 15px;text-align: center;margin-left: 10px;margin-right: 10px;width: 200px;height: 40px;
}

3、页面逻辑

最后,我们来实现页面中的数据存储以及数据获取的逻辑,相关代码参考本文开头部分的官网文档:

import featureAbility from '@ohos.ability.featureAbility'; // 用于获取文件存储路径
import prompt from '@system.prompt';
import storage from '@ohos.data.storage';export default {data: {content: "",},onclickSave() {var context = featureAbility.getContext();context.getFilesDir().then((filePath) => {storage.getStorage(filePath + '/mystore').then((storage) => {// 保存数据到缓存的storage实例中let getPromise = storage.put('qwe', true);getPromise.then(() => {storage.flush();console.info("jarchie---保存成功");}).catch((err) => {console.info("jarchie---保存失败" + err);})}).catch((err) => {console.info("jarchie---获取storage失败" + err);})});},onclickGet() {var context = featureAbility.getContext();context.getFilesDir().then((filePath) => {storage.getStorage(filePath + '/mystore').then((storage) => {let getPromise = storage.get('qwe', false);getPromise.then((value) => {this.content = value;console.info("jarchie---" + this.content);prompt.showToast({message: this.content,duration: 1000})}).catch((err) => {console.info("jarchie---" + err);})}).catch((err) => {console.info("jarchie---获取storage失败" + err)})});}
}

4、实现效果

1ce4e574ccbb382356c0a5fa3f8b9a76_377x814.gif%40900-0-90-f.gif

http://www.lryc.cn/news/101469.html

相关文章:

  • Python Flask构建微信小程序订餐系统 (十二)
  • C++——模板的作用2:特例化
  • Python Web开发技巧VII
  • LaTex4【下载模板、引入文献】
  • 【VSCode部署模型】导出TensorFlow2.X训练好的模型信息
  • windows环境下,安装elasticsearch
  • Elasticsearch入门笔记(一)
  • 记一次安装nvm切换node.js版本实例详解
  • 生态共建丨YashanDB与构力科技完成兼容互认证
  • React从入门到实战-react脚手架,消息订阅与发布
  • 从零构建深度学习推理框架-1 简介和Tensor
  • 使用WGCLOUD监测安卓(Android)设备的运行状态
  • C++笔记之迭代器失效问题处理
  • Tomcat的startup.bat文件出现闪退问题
  • JAVA8-lambda表达式8:在设计模式-模板方法中的应用
  • React之组件间通信
  • 【MATLAB第58期】基于MATLAB的PCA-Kmeans、PCA-LVQ与BP神经网络分类预测模型对比
  • CF1833 A-E
  • 【深度学习】【Image Inpainting】Generative Image Inpainting with Contextual Attention
  • 二维深度卷积网络模型下的轴承故障诊断
  • redis突然变慢问题定位
  • React井字棋游戏官方示例
  • 七大经典比较排序算法
  • 【点云处理教程】03使用 Python 实现地面检测
  • Python 日志记录:6大日志记录库的比较
  • 最近遇到一些问题的解决方案
  • 封装hutool工具生成JWT token
  • 【手机】三星手机刷机解决SecSetupWizard已停止
  • GDAL C++ API 学习之路 OGRGeometry 抽象曲线基类 OGRCurve
  • etcd底层支持的数据库有哪些