使用 v-model 而不是 :model 在 el-form 中,应该使用 :model 而不是 v-model。Vue 3 中的 v-model 用于双向绑定,而 :model 用于将数据传递给表单。
怎么创建一个注册表单,带验证功能
- 输入框记着添加v-model绑定数据
- 在它上边的form-item加上prop,做校验
<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
const registerData=ref({username:'',password:'',rePassword:''
})
const rePasswordValid=(rule,value,callback)=>{if(value==='')callback(new Error('请确认密码'))if(value!==registerData.value.password)callback(new Error('两次密码不一致'))
}
const registerDataRules=ref({username:[{required:true,message:'请输入用户名',trigger:'blur'},{min:6,max:15,message:'用户名长度在6-15位之间',trigger:'blur'}],password:[{required:true,message:'请输入密码',trigger:'blur'},{min:6,max:15,message:'密码长度在6-15位之间',trigger:'blur'}],rePassword:[{validator:rePasswordValid,trigger:'blur'}]
})
const register=()=>{console.log(registerData)
}
</script><template><el-row class="login-page"><el-col :span="12" class="bg"></el-col><el-col :span="6" :offset="3" class="form"><!-- 注册表单 --><el-form ref="formRef" size="large" autocomplete="off" :model="registerData" :rules="registerDataRules"><el-form-item ><h1>注册</h1></el-form-item><el-form-item prop="username"><el-input v-model="registerData.username" :prefix-icon="User" placeholder="请输入用户名"></el-input></el-form-item><el-form-item prop="password"><el-input v-model="registerData.password" :prefix-icon="Lock" type="password"placeholder="请输入密码"></el-input></el-form-item><el-form-item prop="rePassword"><el-input v-model="registerData.rePassword" :prefix-icon="Lock" type="password"placeholder="请输入再次密码"></el-input></el-form-item><!-- 注册按钮 --><el-form-item><el-button class="button" @click="register" type="primary" auto-insert-space>注册</el-button></el-form-item><el-form-item class="flex"><el-link type="info" :underline="false" @click="isRegister = false">← 返回</el-link></el-form-item></el-form></el-col></el-row>
</template><style lang="scss" scoped>
/* 样式 */
.login-page {height: 100vh;background-color: #fff;.bg {background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,url('@/assets/金克斯和日落.png') no-repeat center / cover;border-radius: 0 20px 20px 0;}.form {display: flex;flex-direction: column;justify-content: center;user-select: none;.title {margin: 0 auto;}.button {width: 100%;}.flex {width: 100%;display: flex;justify-content: space-between;}}
}
</style>