[HarmonyOS] Uso de Router (enrutamiento), CustomDialog (ventana emergente), Popup (mensaje de burbuja) y setTimeout (servicio de sincronización) (tomando el módulo de inicio de sesión como ejemplo)

I. Introducción

  • Descripción: Cómo desarrollar un módulo de inicio de sesión completamente funcional en el sistema Hongmeng con indicaciones de posicionamiento precisas.
  • Dificultad: Principiante
  • Puntos de conocimiento:
  • 1. Enrutamiento de la página del enrutador
  • 2. Ventana emergente personalizada CustomDialog
  • 3. Mensaje de burbuja emergente
  • 4. establecer el temporizador de tiempo de espera
  • Efecto:
  • Insertar descripción de la imagen aquí

2. Diseño

1.Diseño de interfaz de usuario

(1) Diseño principal

Con respecto a la construcción del diseño, puede consultar los artículos en la misma columna. El siguiente es un diseño aproximado, que se mejorará más adelante.

Insertar descripción de la imagen aquí

@Entry
@Component
struct Index {
    
    

  @State name: string = ""
  @State pass: string = ""
  @State btnLogin: string = "登录"

  build() {
    
    
    Row() {
    
    
      Column() {
    
    
        // person
        Image($r('app.media.person')).width(100).height(100).margin({
    
    top:80, bottom:50})
        // data
        TextArea({
    
     placeholder : "账号/电话号码"})
          .margin(15)
          .onChange((value: string) => {
    
    
          	// TOD 数据绑定
            this.name = value
          })
        TextInput({
    
     placeholder : "密码", text : this.pass})
          .margin(15)
          .type(InputType.Password)
          .onChange((value: string) => {
    
    
          	// TOD 数据绑定
            this.pass = value
          })
        // btn
        Button(this.btnLogin, {
    
     type: ButtonType.Normal, stateEffect: true })
          .borderRadius(18)
          .backgroundColor(0x317aff)
          .width(90)
          .height(40)
          .margin({
    
    top:50})
          .onClick(() => {
    
    
          	// TODO 登录逻辑
            ...
          })
      }
    }
  }
}

(2) Diálogo personalizado

CustomDialog (ventana emergente): se puede utilizar para operaciones de respuesta interactiva con los usuarios, como anuncios, premios, advertencias, actualizaciones de software, etc.

  • Paso uno: el decorador @CustomDialog se utiliza para decorar el marco emergente personalizado y personalizar el contenido de este decorador.
// 弹出登录成功的信息
@CustomDialog
struct CustomDialogExample {
    
    
  controller: CustomDialogController
  build() {
    
    
    Column() {
    
    
      Text('登录成功')
        .fontSize(20)
        .margin({
    
     top: 10, bottom: 10 })
        .borderRadius(5)
    }
  }
}
  • Paso 2: El decorador @CustomDialog se utiliza para decorar el marco emergente personalizado y personalizar el contenido de este decorador.
@Entry
@Component
struct Index {
    
    

	// 创建构造器
	dialogController: CustomDialogController = new CustomDialogController({
    
    
  		builder: CustomDialogExample({
    
    }),
	})

	...

}
  • Paso 3: haga clic en el componente vinculado al evento onClick para que aparezca la ventana emergente.
@Entry
@Component
struct Index {
    
    

	...

	build() {
    
    
    Row() {
    
    
      Column() {
    
    
      	  Flex({
    
    justifyContent:FlexAlign.Center}) {
    
    
          Button(this.btnLogin, {
    
     type: ButtonType.Normal, stateEffect: true })
            .borderRadius(18)
            .backgroundColor(0x317aff)
            .width(90)
            .height(40)
            .margin({
    
     top: 50 })
            .onClick(() => {
    
    
                // 打开自定义弹窗
                this.dialogController.open()
                // 定时关闭弹窗(1s)
                setTimeout(() => {
    
    
                  // 关闭自定义弹窗
                  this.dialogController.close()
                }, 1000)
            })
        }
      }
     }
    }

}

(3) Ventana emergente

Ventana emergente (mensaje de burbuja): se puede vincular al componente para mostrar el mensaje de la ventana emergente de burbuja y configurar el contenido de la ventana emergente, la lógica de interacción y el estado de visualización.

  • Tome un cuadro de entrada como ejemplo.

Insertar descripción de la imagen aquí

@Entry
@Component
struct Index {
    
    

  @State name: string = ""
  @State pass: string = ""
  @State btnLogin: string = "登录"
  @State handlePopup_name: boolean = false
  @State handlePopup_pass: boolean = false
  @State handlePopup_btn: boolean = false

  // TODO 创建构造器

  build() {
    
    
    Row() {
    
    
      Column() {
    
    
        // person
        ...
        // data
        ...
        TextInput({
    
     placeholder : "密码", text : this.pass})
          .margin(15)
          .type(InputType.Password)
          .onChange((value: string) => {
    
    
            ...
          })
          .bindPopup(this.handlePopup_pass, {
    
    
            message: '密码为空',
          })
        // btn
        Flex({
    
    justifyContent:FlexAlign.Center}) {
    
    
          Button(this.btnLogin, {
    
     type: ButtonType.Normal, stateEffect: true })
            .borderRadius(18)
            .backgroundColor(0x317aff)
            .width(90)
            .height(40)
            .margin({
    
     top: 50 })
            .onClick(() => {
    
    
              ...
              // 密码为空,气泡提示
              if (this.pass == "") {
    
    
                this.handlePopup_pass = !this.handlePopup_pass
              }
              ...
            })
            ...
        }
      }
    }
  }
}

2. Diseño lógico

Con respecto a Router y setTimeout aquí , los amigos que se centran en el front-end definitivamente lo conocen. Los amigos que estudian en carreras también tendrán algunas impresiones. Hablaré brevemente de ello aquí.

(1) Enrutador

Enrutador: Implementar saltos y transferencia de datos entre diferentes páginas de la aplicación.

  • Paso 1: declarar la URL
    Insertar descripción de la imagen aquí

  • Paso 2: salta y pasa el valor.

import router from '@ohos.router';

// 弹出登录成功的信息
...

@Entry
@Component
struct Index {
    
    

  ...

  // 创建构造器
  ...

  build() {
    
    
    Row() {
    
    
      Column() {
    
    
        ...
        // btn
        Flex({
    
    justifyContent:FlexAlign.Center}) {
    
    
          Button(this.btnLogin, {
    
     type: ButtonType.Normal, stateEffect: true })
            .borderRadius(18)
            .backgroundColor(0x317aff)
            .width(90)
            .height(40)
            .margin({
    
     top: 50 })
            .onClick(() => {
    
    
              ...
              router.push({
    
    
                    url: 'pages/UserInfo',
                    // 传递数值
                    params: {
    
    
                      name: this.name,
                      pass: this.pass
                    }
              })
            })
        }
      }
    }
  }
}
  • Paso 3: La interfaz seleccionada recibe el valor.
import router from '@ohos.router';

@Entry
@Component
struct UserInfo {
    
    

  // 接收数据
  @State name: string = router.getParams()?.['name'];
  @State pass: string = router.getParams()?.['pass'];

  build() {
    
    
    Row() {
    
    
      Column(){
    
    
        Text("账号:" + this.name).fontSize(50)
        Text("密码:" + this.pass).fontSize(50)
        Button('返回')
          .onClick(() => {
    
    
            router.back()
          })
      }
    }
  }

}

(2)establecer tiempo de espera

setTimeout (temporizador): especifique cuánto tiempo (ms) debe completar el método (función)

setTimeout(() => {
    
    
  // 关闭自定义弹窗
  this.dialogController.close()
  // 路由跳转
  router.push({
    
    
    url: 'pages/UserInfo',
    params: {
    
    
      name: this.name,
      pass: this.pass
    }
  })
}, 1000)

3. Accesorios

1. Código completo

  • index.ets
import router from '@ohos.router';

// 弹出登录成功的信息
@CustomDialog
struct CustomDialogExample {
    
    
  controller: CustomDialogController
  build() {
    
    
    Column() {
    
    
      Text('登录成功')
        .fontSize(20)
        .margin({
    
     top: 10, bottom: 10 })
        .borderRadius(5)
    }
  }
}

@Entry
@Component
struct Index {
    
    

  @State name: string = ""
  @State pass: string = ""
  @State btnLogin: string = "登录"
  @State handlePopup_name: boolean = false
  @State handlePopup_pass: boolean = false
  @State handlePopup_btn: boolean = false

  // 创建构造器
  dialogController: CustomDialogController = new CustomDialogController({
    
    
    builder: CustomDialogExample({
    
    }),
  })

  build() {
    
    
    Row() {
    
    
      Column() {
    
    
        // person
        Image($r('app.media.person')).width(100).height(100).margin({
    
    top:80, bottom:50})
        // data
        TextArea({
    
     placeholder : "账号/电话号码"})
          .margin(15)
          .onChange((value: string) => {
    
    
            this.name = value
            this.handlePopup_name = false
            this.handlePopup_btn = false
          })
          .bindPopup(this.handlePopup_name, {
    
    
            message: '账号为空',
          })
        TextInput({
    
     placeholder : "密码", text : this.pass})
          .margin(15)
          .type(InputType.Password)
          .onChange((value: string) => {
    
    
            this.pass = value
            this.handlePopup_pass = false
            this.handlePopup_btn = false
          })
          .bindPopup(this.handlePopup_pass, {
    
    
            message: '密码为空',
          })
        // btn
        Flex({
    
    justifyContent:FlexAlign.Center}) {
    
    
          Button(this.btnLogin, {
    
     type: ButtonType.Normal, stateEffect: true })
            .borderRadius(18)
            .backgroundColor(0x317aff)
            .width(90)
            .height(40)
            .margin({
    
     top: 50 })
            .onClick(() => {
    
    
              if (this.name == "") {
    
    
                this.handlePopup_name = !this.handlePopup_name
              } else if (this.pass == "") {
    
    
                this.handlePopup_pass = !this.handlePopup_pass
              } else if (this.name == "123456" && this.pass == "666") {
    
    
                console.log("登录成功!")
                this.dialogController.open()
                // 定时任务,跳转到第二个界面,两秒后
                setTimeout(() => {
    
    
                  // 关闭自定义弹窗
                  this.dialogController.close()
                  // 路由跳转
                  router.push({
    
    
                    url: 'pages/UserInfo',
                    params: {
    
    
                      name: this.name,
                      pass: this.pass
                    }
                  })
                }, 1000)
              } else {
    
    
                this.handlePopup_btn = !this.handlePopup_btn
              }
            })
            .bindPopup(this.handlePopup_btn, {
    
    
              message: '账号或密码错误',
            })
        }
      }
    }
  }
}
  • Información de usuario.ets
import router from '@ohos.router';

@Entry
@Component
struct UserInfo {
    
    

  @State name: string = router.getParams()?.['name'];
  @State pass: string = router.getParams()?.['pass'];

  build() {
    
    
    Row() {
    
    
      Column(){
    
    
        Text("账号:" + this.name).fontSize(50)
        Text("密码:" + this.pass).fontSize(50)
        Button('返回')
          .onClick(() => {
    
    
            router.back()
          })
      }
    }
  }

}

Supongo que te gusta

Origin blog.csdn.net/weixin_48916759/article/details/132957172
Recomendado
Clasificación