HarmonyOS NEXT 学习笔记3--登录页面(数据绑定)
1.代码:
import { promptAction } from '@kit.ArkUI'
@Entry
@Component
struct Page_textInput_onchange {
// @State UI刷新测试 [注意:不是双向绑定]
username: string = ''
password: string = ''
build() {
Column({ space: 20 }) {
TextInput({ placeholder: '账号信息', text: this.username })// 这个text是把页面的值绑定给username
.width('80%')
.onChange((value) => {
// 事件产生的UI更新,不会同步给数据,需要手动赋值
// ①收集数据 this.username
this.username = value
promptAction.showToast({
message: this.username
})
})
// Text(this.username)//这叫UI刷新
TextInput({ placeholder: '密码', text: this.password })
.width('80%')
.onChange((value)=>{ //把值传给password
this.password = value
})
Button('登录')
.width('80%')
.onClick(() => {
// ②使用数据 this.username
if (this.username === 'admin' && this.password === '123456') {
promptAction.showDialog({
message: '登录成功!'
})
} else {
promptAction.showDialog({
message: '登录失败!'
})
}
})
}
.width('100%')
.height('100%')
.padding(20)
}
}
2.效果:
3.优化
import { promptAction } from '@kit.ArkUI'
@Entry
@Component
struct Page_textInput_onchange {
// @State UI刷新测试 [注意:不是双向绑定]
username: string = ''
password: string = ''
// 写法2 抽离这个函数
login() {
if (this.username === 'admin' && this.password === '123456') {
promptAction.showDialog({
message: '登录成功!'
})
} else {
promptAction.showDialog({
message: '登录失败!'
})
}
}
build() {
Column({ space: 20 }) {
TextInput({ placeholder: '账号信息', text: this.username })// 这个text是把页面的值绑定给username
.width('80%')
.onChange((value) => {
// 事件产生的UI更新,不会同步给数据,需要手动赋值
// ①收集数据 this.username
this.username = value
promptAction.showToast({
message: this.username
})
})
// Text(this.username)//这叫UI刷新
TextInput({ placeholder: '密码', text: this.password })
.width('80%')
.onChange((value) => { //把值传给password
this.password = value
})
Button('登录')
.width('80%')
.onClick(() => {
this.login()
})
}
.width('100%')
.height('100%')
.padding(20)
}
}
4.优化示意:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步