页面长这样:

表单校验:
1. 双向数据绑定
2. 配置 Rules 数组 - 查看文档
3. 把校验规则抽离到独立的模块里方便复用(比如手机号校验,不止在登录页用到呢)
4. 校验全部通过后才能点击登录发送请求,点击登录后二次校验
  4.1 van-button 需要写 native-type = "submit"
  4.2 van-form 身上监听submit事件,submit事件会在提交表单校验通过后触发 (验证不通过不会触发)
  4.3 提供函数,然后处理提交事件

Rules数组规则:

实现代码:

# 表单结构
<van-form autocomplete="off" @submit="onSubmit">
  <van-field
    placeholder="请输入手机号"
    type="tel"
    v-model="mobile"
    :rules="mobileRules"
  />
  <van-field
    placeholder="请输入密码"
    type="password"
    v-model="password"
    :rules="passwordRules"
  />
  <div class="cp-cell">
    <van-checkbox v-model="agree">
      <span>我已同意</span>
      <a href="javascript:;">用户协议</a>
      <span>及</span>
      <a href="javascript:;">隐私条款</a>
    </van-checkbox>
  </div>
  <div class="cp-cell">
    <van-button block round type="primary" native-type="submit"
      >登 录</van-button>
  </div>
  <div class="cp-cell">
    <a href="javascript:;">忘记密码?</a>
  </div>
</van-form>
<script setup lang="ts">
import { ref } from 'vue'
import { mobileRules, passwordRules } from '@/utils/rules'
import { Toast } from 'vant'

const mobile = ref('')
const password = ref('')
const agree = ref(false)

const onSubmit = () => {
  # 我已同意勾选后再发送请求,如果没勾选也算登录校验失败
  if (!agree.value) return Toast('请勾选我已同意')
  console.log('校验通过,可以发送Ajax请求了')
}

</script>
# src / utils / 新建 rules.ts

const mobileRules = [
  { required: true, message: '请输入手机号' },
  {
    pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
    message: '手机号格式不正确'
  }
]
const passwordRules = [
  { required: true, message: '请输入密码' },
  {
    pattern: /^\w{8,24}$/,
    message: '密码需8-24个字符'
  }
]

export { mobileRules, passwordRules }

End-------------------------

Logo

前往低代码交流专区

更多推荐