Vue3实战笔记(04)--- 表单校验Vuelidate

本文介绍了如何在Vue3项目中使用Vuelidate进行表单数据验证,包括安装步骤、基础使用示例(如验证规则和自定义消息)、以及高级用法,帮助开发者快速掌握前端表单验证的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

表单校验是前端开发中常见的任务,用于确保用户输入的数据满足特定的要求。在 Vue 3 中,你可以使用多种方法来进行表单校验,包括使用 Vue 自身的响应式系统和组合式 API,或者结合第三方库如 Vuelidate,巧了,我也选择使用Vuelidate。


一、安装Vuelidate

pnpm install @vuelidate/core @vuelidate/validators

使用实例:

import { reactive } from 'vue' // or '@vue/composition-api' in Vue 2.x
import { useVuelidate } from '@vuelidate/core'
import { email, required } from '@vuelidate/validators'

export default {
  setup () {
    const state = reactive({
      name: '',
      emailAddress: ''
    })
    const rules = {
      name: { required },
      emailAddress: { required, email }
    }

    const v$ = useVuelidate(rules, state)

    return { state, v$ }
  }
}

二、基础使用

经过实验总结,直接在实践中记录下几个实用技巧(解释都在js的注释里看看很容易就明白):

<template>
  <div>
    <v-img class="mx-auto my-6" max-width="228"
      src="https://cdn.vuetifyjs.com/docs/images/logos/vuetify-logo-v3-slim-text-light.svg"></v-img>

    <v-card class="mx-auto pa-12 pb-8" elevation="8" max-width="448" rounded="lg">
      <div class="text-subtitle-1 text-medium-emphasis">Account</div>

      <v-text-field density="compact" placeholder="Email address" prepend-inner-icon="mdi:mdi-email-outline"
        variant="outlined" v-model="state.name" :error-messages="v$.name.$errors.map(e => e.$message)"
        @input="v$.name.$touch" @blur="v$.name.$touch"></v-text-field>

      <div class="text-subtitle-1 text-medium-emphasis d-flex align-center justify-space-between">
        Password

        <a class="text-caption text-decoration-none text-blue" href="#" rel="noopener noreferrer" target="_blank">
          Forgot login password?</a>
      </div>

      <v-text-field :append-inner-icon="visible ? 'mdi:mdi-eye-off' : 'mdi:mdi-eye'" :type="visible ? 'text' : 'password'"
        density="compact" placeholder="Enter your password" prepend-inner-icon="mdi:mdi-lock-outline" variant="outlined"
        :error-messages="v$.password.$errors.map(e => e.$message)" @click:append-inner="visible = !visible"
        v-model="state.password" @input="v$.password.$touch" @blur="v$.password.$touch"></v-text-field>


      <v-card class="mb-12" color="surface-variant" variant="tonal">
        <v-card-text class="text-medium-emphasis text-caption">
          Warning: After 3 consecutive failed login attempts, you account will be temporarily locked for three hours. If
          you must login now, you can also click "Forgot login password?" below to reset the login password.
        </v-card-text>
      </v-card>

      <!-- <v-checkbox
        v-model="state.checkbox"
        :rules="[v => !!v || '请先勾选同意!']"
        label="Do you agree?"
        required
        ></v-checkbox> -->

        <!-- 自定义规则和消息 -->
      <!-- <v-checkbox v-model="state.checkbox" :error-messages="v$.checkbox.$errors.map(e => e.$message)"
        label="Do you agree?" required @change="v$.checkbox.$touch" @blur="v$.checkbox.$touch">
      </v-checkbox> -->

      <v-btn block class="mb-8" color="blue" size="large" variant="tonal" @click=login()>
        Log In
      </v-btn>

      <v-card-text class="text-center">
        <a class="text-blue text-decoration-none" href="#" rel="noopener noreferrer" target="_blank">
          Sign up now <v-icon icon="mdi:mdi-chevron-right"></v-icon>
        </a>
      </v-card-text>
    </v-card>
  </div>
</template>

<script setup lang='ts' name="Login">
import { Ref, ref } from 'vue'
import { reactive } from 'vue'
import { useVuelidate } from '@vuelidate/core'
import { email, helpers, minLength, required } from '@vuelidate/validators'
import { watch } from 'vue';

let visible = ref(false)
//初始化状态
const initialState = {
  name: '',
  password: '',
  email: 'sht@163.com',
  checkbox: false,
}

const state = reactive({
  ...initialState,
})

const mustBeCool = (value: any) => value != false
//验规规则
const rules = {
  name: { required: helpers.withMessage('用户名不能为空', required) },
  password: {
    required: helpers.withMessage('密码不能为空', required),
    minLength: helpers.withMessage('密码不能小于6位', minLength(6)),
  },
  email: { required, email },
  checkbox: { required, mustBeCool: helpers.withMessage('请点击同意', mustBeCool) },
}

//配置校验规则和初始化状态
const v$ = useVuelidate(rules, state)

let nameErr: Array<string | Ref<string>> = []
//清空
function clear() {
  v$.value.$reset()    
}
function login() {
  let validate = v$.value.$validate()
  console.log(v$.value.$error)
  console.log(v$.value.$invalid)
  console.log(validate)
  if (!v$.value.$error && !v$.value.$invalid) {//如果校验通过
	//校验通过了干点什么吧
  } else {
    //对象方式赋值错误信息
    //  nameErr = []  
    //  nameErr = v$.value.name.$errors.map(e => e.$message)
  }
  v$.value.password.$errors[0].$validator
}

watch(nameErr, (newValue, oldValue) => {
  console.log('watch 已触发', newValue)
})
</script>

三、高阶用法

//1、自定义message:

required: helpers.withMessage('密码不能为空', required)

//2、自定义规则:

const mustBeCool = (value: any) => value != false

//3、一些可能用到的值变量:

  // console.log(v$.value.$anyDirty)   被触摸了也是true
  console.log(v$.value.$error)
  console.log(v$.value.$invalid)
//4、执行校验:

v$.value.$validate()

总结

直接看官网和文档可能有点云里雾里,可以直接看基础用法,把代码跑一下就明白了。
官网以及文档:

https://vuelidate.js.org/

https://vuelidate-next.netlify.app/

### 关于 Vue-admin-template 的使用笔记 #### 项目简介 Vue-admin-template 是一个轻量级的后台前端解决方案,基于 Vue.js 和 Element UI 构建。此模板提供了完整的权限管理功能以及丰富的组件库,适用于快速搭建企业级后台管理系统[^1]。 #### 添加新页面及其路由配置 为了向应用程序中加入新的视图,在 `src/views` 文件夹下的 `view-tree` 中创建一个新的 `.vue` 文件作为该页面的内容入口——例如命名为 `index.vue`。随后需编辑位于项目的根目录内的 `router/index.js` 来定义相应的路径映射关系,从而使得当访问特定 URL 路径时能够正确加载所期望显示的新页面[^2]。 ```javascript // router/index.js 示例代码片段 import Layout from &#39;@/layout&#39; { path: &#39;/example&#39;, component: Layout, redirect: &#39;noRedirect&#39;, name: &#39;Example&#39;, meta: { title: &#39;Example&#39;, icon: &#39;example&#39; }, children: [ { path: &#39;index&#39;, component: () => import(&#39;@/views/view-tree/index&#39;), name: &#39;ViewTreeIndex&#39;, meta: { title: &#39;View Tree Index&#39;, noCache: true } } ] } ``` #### 登录流程解析 在登录过程中,`handleLogin()` 方法负责处理用户的输入验证并发起异步请求给服务器完成身份认证过程。一旦表单数据被确认有效,则会调用 Vuex store 下的动作 (`user/login`) 向服务端发送 POST 请求尝试获取令牌;如果一切顺利的话,客户端将会重定向至主页或其他指定位置继续后续操作[^3]。 ```javascript // login.vue 示例代码片段 methods: { handleLogin() { console.log(&#39;开始执行 handleLogin 登录方法&#39;); this.$refs.loginForm.validate((valid) => { if (valid) { this.loading = true; console.log(&#39;表单校验通过,开始执行 vuex 中的 login 方法&#39;); this.$store.dispatch(&#39;user/login&#39;, this.loginForm) .then(() => { console.log(&#39;监听调用后端登录接口成功,触发路由前置钩子,准备登录到首页&#39;); this.$router.push({ path: this.redirect || &#39;/&#39; }); this.loading = false; }) .catch(() => { this.loading = false; }); } else { console.error(&#39;提交错误!&#39;); return false; } }); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值