【HarmonyOS Arkts笔记】http网络请求封装
【HarmonyOS Arkts笔记】@ohos.data.preferences用户首选项实现存储信息
登录页
点击登录按钮调用login()方法
import { promptAction, router } from '@kit.ArkUI';
import loginApi from "../../api/login"
import PreferenceUtil from '../../utils/preferencesUtils';@Entry
@Component
struct Login {@State account: string = '';@State password: string = '';@State loading: boolean = false;@State isCheck: boolean = false;login() {if (this.account == '') {promptAction.showToast({message: '请输入账号'})return}if (this.password == '') {promptAction.showToast({message: '请输入密码'})return}if (!this.isCheck) {promptAction.showToast({message: '请同意协议'})return}interface DataFace {token: string}interface ResFace {code: number,data: DataFace,msg: string}/*调用接口*/this.loading = trueloginApi.login({account: this.account,password: this.password,client: 6}).then((res: ResFace) => {if (res.code == 1) {let token: string = res.data.token/*存储用户token*/PreferenceUtil.putPreference('token', token)promptAction.showToast({message: '登录成功'})setTimeout(() => {router.pushUrl({url: 'pages/Index'})}, 2000)}this.loading = false;})}build() {Column() {Image($r('app.media.logo')).width(80).height(80).borderRadius(10).margin({ top: 50 })Text('登录').margin({ top: 15 })Text('登录账号以使用更多服务').fontSize(12).margin({ top: 5 })TextInput({ text: this.account, placeholder: '请输入账号' }).margin({ top: 20 }).onChange((val) => {this.account = val})TextInput({ text: this.password, placeholder: '请输入密码' }).type(InputType.Password).margin({ top: 10 }).onChange((val) => {this.password = val})Row() {Text('忘记密码').fontSize(12).fontColor($r('app.color.color_info'))Text('注册账号').fontSize(12).fontColor($r('app.color.color_primary'))}.justifyContent(FlexAlign.SpaceBetween).margin({ top: 10 }).width('100%')Button() {if (this.loading) {Row() {LoadingProgress().width(30).height(30).margin({ left: 12 }).color(0xFFFFFF)Text('登录中~').fontColor('#fff')}} else {Text('登录').fontColor('#fff')}}.width('100%').height(30).margin({ top: 100 }).backgroundColor($r('app.color.color_primary')).onClick(() => {this.login()})Row() {/*是否同意协议*/if (this.isCheck) {Image($r('app.media.ic_public_todo_filled')).width(15).height(15).onClick(() => {this.isCheck = !this.isCheck})} else {Image($r('app.media.ic_screenshot_circle')).width(15).height(15).onClick(() => {this.isCheck = !this.isCheck})}Text('我已阅读并同意').fontColor($r('app.color.color_info')).fontSize(12).margin({ left: 5 })Text('《用户协议》').fontColor($r('app.color.color_primary')).fontSize(12)Text('和').fontColor($r('app.color.color_info')).fontSize(12)Text('《隐私政策》').fontColor($r('app.color.color_primary')).fontSize(12)}.margin({ top: 20 })}.justifyContent(FlexAlign.Center).width('100%').padding({ left: 30, right: 30 })}
}