Aurelia - 无法访问模板中的变量

时间:2017-11-02 04:38:34

标签: aurelia aurelia-binding

简单的问题。

我有一个登录模板 - 用户名和密码的表单:

%{BUILD_SOURCEBRANCHNAME}%

我已经四处查看了如何在login.ts文件中访问这些变量。

特别是我想在按下按钮登录后最终将它们发送到api。

我有一个submitLogin()函数,但我不知道你如何访问变量用户名和密码。

有人可以告诉我如何访问这些变量。

我的用户名和密码是红色的下划线..

<template>
<section>
    <h2>${heading}</h2>

    <form role="form" submit.delegate="login()">
        <div class="form-group">
            <label for="userName">User Name</label>
            <input type="text" value.bind="userName" class="form-control" id="userName" placeholder="User Name">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" value.bind="password" class="form-control" id="password" placeholder="Password">
        </div>
        <button type="button"  click.delegate="submitLogin()" class="btn btn-default">Login</button>
    </form>

    <hr>
    <div class="alert alert-danger" if.bind="loginError">${loginError}</div>
</section>

1 个答案:

答案 0 :(得分:2)

表单提交逻辑可以绑定到<form>本身已经给出按钮类型submit

<form  role="form" submit.delegate="submitLogin()">
    <div class="form-group">
        <label for="username">User Name</label>
        <input type="text" value.bind="username" class="form-control" id="username" placeholder="User Name">
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" value.bind="password" class="form-control" id="password" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-default">Login</button>
</form>

您可以从视图中访问您的课程字段,或者如下所示

import { HttpClient } from "aurelia-fetch-client"
import { autoinject } from "aurelia-framework"
import { TokenService } from "../tokenService"

@autoinject
export class Login {
    heading: string = "Login"
    username: string = ''
    password: string = '' // these are pubic fields available in your view unless you add 'private' in front of them

    constructor(private tokenService: TokenService, private http: HttpClient) { // this way you can keep them private since they are not needed in the view

    }

    submitLogin() {
        const { username, password } = this
        if (!!username && !!password) { // or your validations
            this.tokenService.login({ username, password })
        }
    }
}