本以为这很简单,但事实并非如此。 使用 vuetify 表单,如何将表单绑定到 Enter 按钮,以便使用 Enter 按钮调用它的提交功能?
我一发布问题就会找到解决方法。 我在这里找到了答案:
https://github.com/vuetifyjs/vuetify/issues/1545
基本上,我必须向组件添加一个事件侦听器,以将 Enter 键按下附加到我的身份验证方法。 这是问题中的组件:
<template>
<v-card>
<v-card-title>
<span class="headline">Login</span>
</v-card-title>
<v-form v-model="isValid">
<v-card-text>
<v-container>
<v-row>
<v-col cols="12">
<v-text-field
v-model="username"
label="User Name"
prepend-icon="mdi-account circle"
:rules="userNameRequired"
required
></v-text-field>
</v-col>
<v-col cols="12">
<v-text-field
v-model="password"
label="Password"
:type="showPassword ? 'text' : 'password'"
prepend-icon="mdi-lock"
:append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
@click:append="showPassword = !showPassword"
:rules="passwordRequired"
required
></v-text-field>
</v-col>
</v-row>
</v-container>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="blue darken-1" text @click="close"> Close </v-btn>
<v-btn color="blue darken-1" text @click="authenticate" :disabled="!isValid">
Login
</v-btn>
</v-card-actions>
</v-form>
</v-card>
</template>
<script>
import { authenticationService } from "../services/authenticationService/authentication.service";
import User from "../models/user";
export default {
name: "LoginForm",
props: ["userForAuthentication"],
data: () => ({
username: "",
password: "",
user: {},
isValid: true,
showPassword: false,
userNameRequired: [(v) => !!v || "User Name is required"],
passwordRequired: [(v) => !!v || "Password is required"],
}),
methods: {
async authenticate() {
try {
const response = await authenticationService.authenticateUser(
this.$data.username,
this.$data.password
);
if (response.status === 200) {
this.$data.user.shallowClone(response.data.user);
await this.resetData();
this.$emit(
"user-logging-in-event",
this.$data.user,
response.data.token
);
this.$toasted.success(`${this.$data.user.fullName} is logged in.`, {
duration: 3000,
});
} else if (response.status === 400) {
this.$toasted.error("Username or Password is incorrect.", {
duration: 3000,
});
} else {
this.$toasted.error(
"An error occurred while trying to authenticate the user",
{
duration: 3000,
}
);
}
} catch (error) {
this.$toasted.error(error, {
duration: 3000,
});
}
},
close() {
this.$emit("user-logging-in-event", null, null);
},
async resetData() {
this.$data.username = "";
this.$data.password = "";
},
},
mounted() {
let self = this;
window.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
self.authenticate();
}
});
this.$data.user = new User();
this.$data.user.shallowClone(this.$props.userForAuthentication);
},
};
</script>
其他答案中的链接问题建议使用
@submit
而不是关键侦听器。
<v-form @submit="onSubmit">
<v-input v-model="fillme">
<v-btn type="submit">Go!</v-btn>
</v-form>
这是可行的,但是请参阅有关如何在没有提交输入类型和多个文本字段(按照普通表单的浏览器行为)的情况下按 Enter 键时不会触发的警告。这个怪癖通常就是它似乎不起作用的原因。
我发现使用
@keyup.enter
(在 Vue3 中不需要 .native)是不可靠的,有时甚至会在调用处理程序之前重新加载页面,即使使用 @keyup.enter.prevent
也是如此。 @submit
在这方面是可靠的。