我需要一段VUE3表单合法性校验的代码
时间: 2024-05-11 16:15:09 浏览: 83
当然,我可以为您提供VUE3表单合法性校验的代码。以下是示例代码:
```
<template>
<form @submit.prevent="submitForm">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" v-model="username" :class="{ error: errors.username }">
<div v-if="errors.username" class="error-message">{{ errors.username }}</div>
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" v-model="password" :class="{ error: errors.password }">
<div v-if="errors.password" class="error-message">{{ errors.password }}</div>
</div>
<button type="submit">提交</button>
</form>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
errors: {}
}
},
methods: {
submitForm() {
this.errors = {};
if (!this.username) {
this.errors.username = '用户名不能为空';
}
if (!this.password) {
this.errors.password = '密码不能为空';
}
if (Object.keys(this.errors).length === 0) {
// 表单验证通过,可以进行提交操作
// 例如:axios.post('/api/login', {username: this.username, password: this.password})
}
}
}
}
</script>
<style>
.error {
border-color: red;
}
.error-message {
color: red;
}
</style>
```
希望这能够帮到你!
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)