本文介绍了用Navigation组件,以及LoaclStorage本地存储实现电话簿功能:增删改查。(需要用虚拟机)
主页效果图:
联系人详情图:
添加:
代码:
在ets下的entryability的EntryAbility中创建LocalStorage实例并初始化,
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
// 定义id可用于数组的索引
let nextID = 0
// 定义类包括本人和联系人
@Observed
export class TelephoneBook {
me: Friend
friends: ObservedArray<Friend>
constructor(me: Friend, friends: ObservedArray<Friend>) {
this.me = me
this.friends = new ObservedArray<Friend>(friends)
}
}
// 联系人类: 姓名,地址,电话
@Observed
export class Friend {
name: string
address: Address
phone: ObservedArray<number>
index: number
constructor(name: string, save: string, city: string, district: string, phone: number[]) {
this.name = name
this.address = new Address(save, city, district)
this.phone = new ObservedArray(phone)
this.index = nextID++
}
}
// 地址类: 省份,城市,城市区域
@Observed
export class Address {
save: string
city: string
district: string
constructor(save: string, city: string, district: string) {
this.save = save
this.city = city
this.district = district
}
}
// 继承数组类,因为联系人电话不止一个,所以是个数组
@Observed
export class ObservedArray<T> extends Array<T> {
constructor(args: T[]) {
if (args instanceof Array) {
super(...args)
} else {
super(args)
}
}
}
export default class EntryAbility extends UIAbility {
// 定义LocalStorage实例并初始化
para: Record<string, TelephoneBook> = { 'phone': new TelephoneBook(
new Friend('111', '内蒙古', '乌兰察布市', 'xxx', [18711112222, 17346642224]),
[
new Friend('阿龙', '江西省', '吉安市', '章贡区', [17346649994, 18547486495]),
new Friend('霍岩', '江西省', '赣州市', '章贡区', [17346649994, 18547486495]),
new Friend('李光鸿', '黑龙江', '哈尔滨', '南岗区', [17346649114, 13255478976]),
new Friend('钱海', '江西省', '南昌市', '南昌县', [17346649224, 15644547867]),
new Friend('武巧忠', '浙江省', '杭州市', '西湖区', [17346649334, 15366428564]),
new Friend('饶嘉龙', '云南省', '昆明市', '呈贡区', [17346649444, 19346547842]),
new Friend('马海', '湖南省', '长沙市', '岳麓区', [17346649554, 17645487842]),
new Friend('杨森','新疆', '乌鲁木齐市', '新市区', [15445685823, 19844568897]),
new Friend('王五','新疆', '乌鲁木齐市', '新市区', [15445685823, 19844568897]),
new Friend('张三','新疆', '乌鲁木齐市', '新市区', [15445655789, 19844552397]),
new Frien