vue3+ts+vant4+pinia+axios+scss创建项目基本流程
自我记录
src/utils/rules.ts
// 引入vant组件:rules=[] 的类型
import type { FieldRule } from 'vant'
// 表单校验
const mobileRules: FieldRule[] = [
{ required: true, message: '请输入手机号' },
{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
]
const passwordRules: FieldRule[] = [
{ required: true, message: '请输入密码' },
{ pattern: /^\w{8,24}$/, message: '密码需8-24个字符' }
]
export { mobileRules, passwordRules }
使用src/views/Login/index.vue
使用的页面导入刚才写好的公共规则ts文件 import { mobileRules, passwordRules } from ‘@/utils/rules’
然后在:rules="mobileRules"
:rules="passwordRules"
具体如下
整体校验 vant文档
submit
提交表单且验证通过后触发 回调函数 values: object
native-type
原生 button 标签的 type 属性
表单组件@submit="login"
按钮组件使用native-type="submit"
<script setup lang="ts">
import { ref } from 'vue'
// 引入
import { mobileRules, passwordRules } from '@/utils/rules'
const checked = ref(false)
const show = ref(false)
const mobile = ref('')
const password = ref('')
// 表单提交
const login = () => {
//整体校验通过
console.log('可以发请求了')
}
</script>
<template>
<div class="login-page">
<cp-nav-bar right-text="注册" @click-right="$router.push('/register')" />
<!-- 头部 -->
<div class="login-head">
<h3>密码登录</h3>
<a href="javascript:;">
<span>短信验证码登录</span>
<van-icon name="arrow"></van-icon>
</a>
</div>
<!-- 表单 -->
<van-form autocomplete="off" @submit="login">
<van-field
:rules="mobileRules"
placeholder="请输入手机号"
type="tel"
v-model="mobile"
></van-field>
<van-field
:rules="passwordRules"
placeholder="请输入密码"
:type="show ? 'text' : 'password'"
v-model="password"
>
<template #button>
<cp-icon
:name="`login-eye-${show ? 'on' : 'off'}`"
@click="show = !show"
/>
</template>
</van-field>
<div class="cp-cell">
<van-button block round type="primary" native-type="submit">登 录</van-button>
</div>
</van-form>
</div>
</template>
单独校验
通过之后 在使用整体校验