<template>
  <view>
    <form ref="formRef" :rules="rules" @submit.prevent="handleSubmit">
      <input v-model="form.username" type="text" name="username" placeholder="请输入用户名" />
      <input v-model="form.password" type="password" name="password" placeholder="请输入密码" />
      <button type="primary" @click="handleSubmit">提交</button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleSubmit() {
      this.$nextTick(() => {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            console.log('表单验证通过，可以提交数据');
            // 提交表单逻辑
          } else {
            console.log('表单验证失败');
            // 处理验证失败逻辑
          }
        });
      });
    }
  }
};
</script>