您看一下首选项数据持久化。能否满足您的述求
参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-preferences-V5#导入模块
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import { DEFAULT } from '@ohos/hypium';
import router from '@ohos.router';
const usernameV: string = "admin";
const passwordV: string = "123456";
//加载等待
async function sleepFunction(): Promise<void> {
try {
const result: string = await new Promise((resolve) => {
setTimeout(() => {
router.pushUrl({ url: 'pages/Page' });
}, 1000);
});
} catch (e) {
console.error(`Get exception: ${e}`);
}
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State username: string = "";
@State password: string = "";
private inputAccountValue: string = "";
private inputPassword: string = "";
@State flag1: boolean = false;
@State flag2: boolean = false;
@StorageLink("preferences") preferences: dataPreferences.Preferences = {} as dataPreferences.Preferences;
@State loginHistoryAccounts: Array<string> = []
aboutToAppear() {
//获取首选项的用户数据
for (let index = 0; index < this.loginHistoryAccounts.length; index++) {
let usernameVal: Object = this.preferences.getSync(`username+${index}`, 'default');
if (this.username == "default") {
this.username = "";
} else {
this.loginHistoryAccounts.map((str) => {
if (str !== usernameVal as string) {
this.loginHistoryAccounts.push(usernameVal as string)
}
})
}
}
try {
let passwordVal: Object = this.preferences.getSync('password', 'default');
this.password = passwordVal as string;
if (this.password == "default") {
this.password = "";
}
let savePasswordVal: Object = this.preferences.getSync('savePassword', 'default');
if (savePasswordVal != DEFAULT) {
this.flag1 = savePasswordVal as boolean;
}
let autoLoginVal: Object = this.preferences.getSync('autoLogin', 'default');
if (autoLoginVal != DEFAULT) {
this.flag2 = autoLoginVal as boolean;
}
} catch (err) {
let code: number = (err as BusinessError).code;
let message: string = (err as BusinessError).message;
console.error(`Failed to get value of 'info'. Code:${code}, message:${message}`);
}
}
onPageShow() {
//每次显示这个页面时,如果勾选了自动登录,则自动登录
if (this.flag2 == true && this.username == usernameV && this.password == passwordV) {
sleepFunction()
}
}
@Builder
MyMenu() {
Menu() {
ForEach(this.loginHistoryAccounts, (item: string) => {
MenuItem({
content: item.toString(),
}).onClick(() => {
this.username = item
})
}, (item: string) => item)
}.width('90%')
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Row() {
Text("账号:")
.margin({ top: 20 })
.fontSize(20)
TextInput({ placeholder: '请输入账号', text: this.username })
.onChange(value => {
this.inputAccountValue = value;
})
.width(250)
.margin({ top: 20 })
.type(InputType.USER_NAME)
Text('下拉')
.width(30).height(30).backgroundColor('#ffdd0a0a').bindMenu(this.MyMenu)
}
Row() {
Text("密码:")
.margin({ top: 20 })
.fontSize(20)
TextInput({ placeholder: '请输入密码', text: this.password })
.onChange(value => {
this.inputPassword = value;
})
.width(250)
.margin({ top: 20 })
.type(InputType.Password)
}
Row() {
Row() {
Toggle({ type: ToggleType.Checkbox, isOn: this.flag1 })
.margin({ top: 13 })
.width(20)
.onClick(() => {
this.flag1 = !this.flag1;
})
Text("记住密码")
.margin({ top: 10 })
.fontSize(15)
}
.margin({ right: 50 })
Row() {
Toggle({ type: ToggleType.Checkbox, isOn: this.flag2 })
.margin({ top: 13 })
.width(20)
.onClick(() => {
if (this.flag2 == false) {
this.flag1 = true;
}
this.flag2 = !this.flag2;
})
Text("自动登录")
.margin({ top: 10 })
.fontSize(15)
}
.margin({ left: 50 })
}
Button('登录')
.width(150)
.margin({ top: 20 })
.onClick(() => {
try {
//添加数据,写入账号
if (this.preferences.hasSync(`username+${this.loginHistoryAccounts.length}`)) {
//如果存在就更改账号
this.preferences.put(`username+${this.loginHistoryAccounts.length}`, this.inputAccountValue,
(err: BusinessError) => {
if (err) {
console.error(`Failed to put the value of 'username'. Code:${err.code},message:${err.message}`);
return;
}
})
} else {
// 此处以此键值对不存在时写入数据为例
this.preferences.putSync(`username+${this.loginHistoryAccounts.length}`, this.inputAccountValue);
this.loginHistoryAccounts.push(this.inputAccountValue)
}
//点击记住密码,持久化账号密码
if (this.flag1 == true) {
//写入密码
if (this.preferences.hasSync('password')) {
//如果存在就更改密码
this.preferences.put('password', this.inputPassword, (err: BusinessError) => {
if (err) {
console.error(`Failed to put the value of 'password'. Code:${err.code},message:${err.message}`);
return;
}
})
} else {
// 键值对不存在时写入数据
this.preferences.putSync('password', this.inputPassword);
}
//写入记住密码状态
if (this.preferences.hasSync('savePassword')) {
} else {
// 键值对不存在时写入数据
this.preferences.putSync('savePassword', this.flag1);
}
//写入自动登录状态
if (this.flag2 == true) {
if (this.preferences.hasSync('autoLogin')) {
} else {
// 此处以此键值对不存在时写入数据为例
this.preferences.putSync('autoLogin', this.flag1);
}
} else {
this.preferences.deleteSync('autoLogin');
}
} else {
this.preferences.deleteSync('password');
this.preferences.deleteSync('savePassword');
}
//数据持久化
this.preferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in flushing.');
})
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`Failed to check the key 'save'. Code:${code}, message:${message}`);
}
router.pushUrl({ url: 'pages/Page' });
}
}
}
}
}
}