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.优化示意:

 

posted @ 2024-07-14 15:30  o蹲蹲o  阅读(3)  评论(0编辑  收藏  举报