vue elementUI 表单校验功能之数组多层嵌套

yizhihongxing

我将为您提供关于“vue elementUI 表单校验功能之数组多层嵌套”的完整攻略。

1. 前置知识

在学习“vue elementUI 表单校验功能之数组多层嵌套”前,需要掌握以下知识点:

  • Vue.js基础使用方法
  • Vue组件和Props使用方法
  • ElementUI表单组件使用方法

2. 数组多层嵌套表单校验方法

默认情况下,ElementUI只针对表单对象进行校验,但是在实际开发中,我们经常会遇到需要校验数组中某个元素的情况。例如在表单中需要填写多个电话号码,每个电话号码又包含了区号、号码和分机号等信息。

假设我们的数据结构如下所示:

form: {
  name: '',
  phones: [
    {
      areaCode: '',
      number: '',
      ext: ''
    }
  ]
},

(1). 自定义校验规则

首先我们需要定义一个自定义的校验规则,并将其封装成为一个函数。该函数接收两个参数:value和callback。其中,value表示需要校验的值,callback表示校验完成后需要执行的函数。

下面是一个自定义校验规则的示例代码:

// 自定义电话号码校验规则
const validatePhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('手机号码不能为空'));
  }
  const reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
  if (!reg.test(value)) {
    callback(new Error('您输入的手机号码不合法'));
  } else {
    callback();
  }
};

(2). 组件中使用校验规则

在组件中,我们需要使用到ElementUI提供的校验规则validator。我们可以在每个需要校验的表单项中定义validator属性,并将上面定义的自定义规则传递进去。

下面是示例代码:

<el-form-item label="电话号码" prop="phones">
  <el-row v-for="(phone, index) in form.phones" :key="index">
    <el-col span="6">
      <el-form-item :prop="`phones.${index}.areaCode`" label="区号">
        <el-input v-model="phone.areaCode"></el-input>
      </el-form-item>
    </el-col>
    <el-col span="9">
      <el-form-item :prop="`phones.${index}.number`" label="号码">
        <el-input v-model="phone.number" v-validate:phone-number="{ validator: validatePhone, trigger: 'blur' }"></el-input>
        <span v-show="errors.has(`phones.${index}.number`)" class="error">{{ errors.first(`phones.${index}.number`) }}</span>
      </el-form-item>
    </el-col>
    <el-col span="9">
      <el-form-item :prop="`phones.${index}.ext`" label="分机号">
        <el-input v-model="phone.ext"></el-input>
      </el-form-item>
    </el-col>
  </el-row>
</el-form-item>

在上面的代码中,我们将在每个号码输入框中定义v-validate指令,并传递自定义校验规则validatePhone。同时,我们也定义了一个prop属性,该属性的值为phones.${index}.number,表示phones数组中第index个元素的number属性需要进行校验。注意,该属性必须以字符串的形式进行传递。

3. 示例说明

(1). 校验规则示例

假设我们需要在表单中,验证输入的电话号码是否符合要求。例如,我们需要输入3个电话号码,每个电话号码由一个区号、一个号码和一个分机号组成,其中号码为必填项。对于号码的校验,我们使用上面所提供的自定义校验规则validatePhone。下面是示例代码:

<template>
  <el-form :model="form" ref="form" :rules="rules" label-width="80px" style="width: 800px;">
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="电话号码" prop="phones">
      <el-row v-for="(phone, index) in form.phones" :key="index">
        <el-col span="6">
          <el-form-item :prop="`phones.${index}.areaCode`" label="区号">
            <el-input v-model="phone.areaCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col span="9">
          <el-form-item :prop="`phones.${index}.number`" label="号码">
            <el-input v-model="phone.number" v-validate:phone-number="{ validator: validatePhone, trigger: 'blur' }"></el-input>
            <span v-show="errors.has(`phones.${index}.number`)" class="error">{{ errors.first(`phones.${index}.number`) }}</span>
          </el-form-item>
        </el-col>
        <el-col span="9">
          <el-form-item :prop="`phones.${index}.ext`" label="分机号">
            <el-input v-model="phone.ext"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">提交表单</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '',
        phones: [
          {
            areaCode: '',
            number: '',
            ext: ''
          },
          {
            areaCode: '',
            number: '',
            ext: ''
          },
          {
            areaCode: '',
            number: '',
            ext: ''
          }
        ]
      },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度应在2-10个字符之间', trigger: 'blur' }
        ],
        phones: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('至少需要填写一个电话号码'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },
  methods: {
    validatePhone(rule, value, callback) {
      if (!value) {
        return callback(new Error('手机号码不能为空'));
      }
      const reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error('您输入的手机号码不合法'));
      } else {
        callback();
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {});
    }
  }
};
</script>

该示例会通过validator自定义校验规则,对输入的电话号码进行校验。其中,号码的校验规则由validatePhone函数实现。

(2). 数组嵌套示例

假设我们现在需要完成一个关于旅游景点的信息录入表单,其中包含景点的名称、地点和包含景点的城市。每个城市由一个名称、一个省份和一个包含景点信息的数组组成,例如:

form: {
  name: '',
  locations: [
    {
      name: '',
      province: '',
      spots: [
        {
          name: '',
          desc: ''
        }
      ]
    }
  ]
};

我们需要对这样一个多层嵌套数组进行校验。下面是示例代码:

<template>
  <el-form :model="form" ref="form" :rules="rules" label-width="80px" style="width: 800px;">
    <el-form-item label="名称" prop="name">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="旅游地点" prop="locations">
      <el-row v-for="(location, index) in form.locations" :key="index">
        <el-col span="8">
          <el-form-item :prop="`locations.${index}.name`" label="城市名称">
            <el-input v-model="location.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col span="8">
          <el-form-item :prop="`locations.${index}.province`" label="所在省份">
            <el-input v-model="location.province"></el-input>
          </el-form-item>
        </el-col>
        <el-col span="8">
          <el-form-item :prop="`locations.${index}.spots`" label="景点信息">
            <el-row v-for="(spot, spotIndex) in location.spots" :key="spotIndex">
              <el-col :span="spotIndex === 0 ? 9 : 10">
                <el-form-item :prop="`locations.${index}.spots.${spotIndex}.name`" label="景点名称">
                  <el-input v-model="spot.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="spotIndex === 0 ? 15 : 14">
                <el-form-item :prop="`locations.${index}.spots.${spotIndex}.desc`" label="景点描述">
                  <el-input v-model="spot.desc"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">提交表单</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '',
        locations: [
          {
            name: '',
            province: '',
            spots: [
              {
                name: '',
                desc: ''
              }
            ]
          }
        ]
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度应在2-10个字符之间', trigger: 'blur' }
        ],
        locations: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('至少需要填写一个旅游地点'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {});
    }
  }
};
</script>

该示例会对所有表单项进行校验,其中locations数组的校验规则为至少需要填写一个旅游地点。在locations中每个城市的子表单都需要一个自定义的prop属性,例如locations.${index}.spots.${spotIndex}.name,表示spots数组中第spotIndex个元素的name属性需要进行校验。同时,在嵌套的子表单中,也需要对每个表单项进行相应的校验规则的定义。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue elementUI 表单校验功能之数组多层嵌套 - Python技术站

(0)
上一篇 2023年5月29日
下一篇 2023年5月29日

相关文章

  • Vue项目中最新用到的一些实用小技巧

    接下来我将向你介绍Vue项目中最新用到的一些实用小技巧。 1. 使用.sync修饰符简化父子组件通信 在Vue中,组件之间的通信非常重要。在父子组件之间通信时,父组件传递数据给子组件是很常见的一种情况。我们通常会使用props来传递数据,并且在子组件中通过$emit来触发父组件中的方法来达到通信的目的。但是,这种方法不太方便,因为在父组件中需要手动监听$em…

    Vue 2023年5月28日
    00
  • Vue2 模板template的四种写法总结

    Vue2 模板template的四种写法总结: Vue2 中,我们可以使用 template 来书写 HTML 模板,但是它也有多种写法,下面我们来总结一下。 1. 字符串模板形式 我们可以在组件中定义字符串模板。 <template> <div> <h1>{{ title }}</h1> <p>{…

    Vue 2023年5月29日
    00
  • 详解如何理解vue的key属性

    以下是详解如何理解vue的key属性的完整攻略: 1. 什么是Vue的key属性? Vue中的key属性是在使用v-for指令时用来提高性能和防止数据混乱的重要属性。key属性可以为每个v-for循环中的子元素设定一个唯一的标识符,Vue在渲染虚拟DOM节点时会根据key属性来判断哪些节点需要被更新,从而减少页面重新渲染的量,提高页面性能。 2. 如何理解V…

    Vue 2023年5月28日
    00
  • VueJs 搭建Axios接口请求工具

    VueJs 搭建 Axios 接口请求工具可以分为以下几个步骤: 1. 安装 Axios 首先,在 VueJs 中使用 Axios 需要先安装 Axios 库。可以使用 npm 命令进行安装(前提是已经安装了 npm): npm install axios 2. 创建请求服务 可以在 Vue 项目中新建一个 services 文件夹,在其中创建 api.js…

    Vue 2023年5月28日
    00
  • Vue网络请求的三种实现方式介绍

    Vue网络请求的三种实现方式介绍 1. 使用Vue-resource Vue-resource是Vue.js的官方插件,可以很方便地完成网络请求的操作。基本使用如下: // 引入Vue-resource插件 import Vue from ‘vue’; import VueResource from ‘vue-resource’; // 使用Vue-reso…

    Vue 2023年5月28日
    00
  • Vue列表循环从指定下标开始的多种解决方案

    Vue列表循环从指定下标开始的多种解决方案 在Vue开发中,我们经常需要将一个数组渲染为一个列表。然而,有时我们希望仅仅从数组的指定下标开始进行循环渲染,这就需要使用到Vue列表循环从指定下标开始的多种解决方案。 一、使用数组的slice方法进行筛选 使用数组的slice()方法可以返回一个新的数组,该数组包含原始数组中指定起点到结束点之间的元素。通过在模板…

    Vue 2023年5月29日
    00
  • springboot+vue实现websocket配置过程解析

    下面我将详细讲解如何使用SpringBoot和Vue.js实现WebSocket的配置过程,整个过程需要分为以下几个步骤: 配置后端SpringBoot实现WebSocket 配置前端Vue.js实现WebSocket 前后端WebSocket通信示例 接下来我将详细讲解每个步骤的具体实现。 1. 配置后端SpringBoot实现WebSocket 首先,我…

    Vue 2023年5月28日
    00
  • 浅谈vue路径优化之resolve

    让我来详细讲解一下“浅谈 Vue 路径优化之 resolve”的完整攻略。 什么是 resolve 在 Vue 项目中,我们经常需要使用相对路径来引入模块或组件。这样做会导致代码可读性变差、代码维护性降低。因此,我们需要一种更好的解决方案,它就是 resolve。 resolve 是 webpack 中的一个处理模块路径的插件,可以帮助我们快速定位到目标文件…

    Vue 2023年5月27日
    00
合作推广
合作推广
分享本页
返回顶部