华为手表开发:WATCH 3 Pro(11)存储数据_轻量级存储_到本地
- 初
- 环境与设备
- 文件夹:
- 文件
- 新增一个文本输入框
- index.hml
- index.css
- 存储数据的逻辑
- index.js
- 结果如下图
初
希望能写一些简单的教程和案例分享给需要的人
鸿蒙可穿戴开发
环境与设备
系统:window
设备:HUAWEI WATCH 3 Pro
开发工具:DevEco Studio 3.0.0.800
鸿蒙开发
文件夹:
entry:项目文件夹
js:前端文件夹
pages:页面文件夹
index:首页文件夹
文件
index.css:首页样式
index.hml:首页
index.js:首页脚本
新增一个文本输入框
代码如下:
index.hml
<div class="container">
<div class="input-item">
<div class="color">
<label class="input-title">用户名:</label>
<input class="input" value="{{userName}}" type="text" placeholder="请输入用户名" onchange="changeUserName"></input>
</div>
</div>
<input class="btn" type="button" value="确认" onclick="onSetting"></input>
<dialog class="dialogClass" id="successDialog" dragable="true">
<div class="content">
<text>操作成功</text>
</div>
</dialog>
</div>
index.css
.container {
height: 100%;
width: 100%;
flex-direction: column;
padding: 0 0 5% 0;
justify-content: center;
align-items: center;
}
.color {
margin: 0 4% 0 4% ;
width: 92%;
border-bottom: 1px solid rgba(0,0,0,0.1);
}
.input-item {
width: 100%;
margin-bottom: 10px;
}
.input-title {
width: 60px;
color: #fff;
font-family: HarmonyHeiTi;
font-size: 12px;
text-align: right;
}
.input {
width: 65%;
height: 36px;
padding: 0% 10px;
font-size: 14px;
border-radius: 8px;
background-color: #fff;
color: black;
}
.btn{
display: flex;
width: 100px;
font-size: 14px;
height: 36px;
}
存储数据的逻辑
读取指定文件,将数据加载到Storage实例,用于数据操作,使用callback方式返回结果,此方法为异步方法。
代码如下:
index.js
import data_storage from ‘@ohos.data.storage’;
import featureAbility from ‘@ohos.ability.featureAbility’;
import prompt from '@system.prompt';
import data_storage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility';
export default {
data: {
userName: ""
},
onInit() {
var currPage = this;
// 获取本地存储的用户信息
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
data_storage.getStorage(filePath + '/userNameValue', function (err, storage) {
let promiseGet = storage.get('userName', '未知');
promiseGet.then((value) => {
currPage.userName = value;
}).catch((err) => {
})
})
});
},
onSetting() {
var currPage = this;
// 写入本地存储
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
data_storage.getStorage(filePath + '/userNameValue', function (err, storage) {
if (err) {
console.info("Get the storage failed, path: " + filePath + '/userNameValue')
return;
}
storage.putSync('userName', currPage.userName)
storage.flushSync();
prompt.showToast({
message: "保存成功",
duration: 3000,
});
})
});
},
changeUserName(e) {
this.userName = e.value;
},
changePhone(e) {
this.reminderMobileNumber = e.value;
}
}
结果如下图