如何在 Vue 2 中创建具有 Vuetify 等验证功能的 VForm 组件?

Mys*_*ood 4 vue.js vuejs2 vuetify.js

在 Vuetify 中,您可以设置如下代码,VForm组件可以自动检查其中的所有输入是否VForm有效,而无需来回传递任何道具。如何在 Vue 2 中为我自己的表单和输入组件实现此功能?

<template>
  <v-form v-model="formIsValid">
    <v-text-field :rules="[required]"></v-text-field>
  </v-form>
</template>

<script>
  data() {
    return {
      formIsValid: false
    }
  },
  methods: {
    required(val) {
      return !!val || 'Required.'
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

小智 7

您可以探索 vuetify 源代码以了解他们是如何做到这一点的。
首先,你必须了解provide/inject,https://v2.vuejs.org/v2/api/#provide-inject
他们的概念的一个非常简化的版本如下所示,

VForm.vue

export default {
  data() {
    return {
      inputs: []
    }
  },
  provide () {
    // provide this Form component for child, so child can register itself
    return { form: this }
  },
  methods: {
    register(input) {
      this.inputs.push(input);
    },
    validate() {
      // loop through child registered inputs,
      // run every child.validate() to validate all child
      this.inputs.forEach(input => {
        input.validate();
      });
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

VInput.vue

export default {
  props: {
    rules: {
      default: () => [],
      type: Array
    }
  },
  // inject parent VForm component
  inject: ['form'],
  created() {
    // with inject above, you can use this.form to reference parent VForm
    this.form.register(this);
  },
  methods: {
    validate() {
      // use rules to validate input
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用法
v-form 提供的任何内容都可以在带有注入的 v-input 中使用。

<template>
  <v-form>
    <v-input :rules="rules"/>
  <v-form/>
</template>
Run Code Online (Sandbox Code Playgroud)

大部分逻辑都在这些文件中,vuetify 所做的远比上面的逻辑多得多。学会研究开源代码,开源项目很棒。

  1. VForm: https: //github.com/vuetifyjs/vuetify/blob/v2.6.15/packages/vuetify/src/components/VForm/VForm.ts
  2. VForm 使用的可注册 mixin: https://github.com/vuetifyjs/vuetify/blob/v2.6.15/packages/vuetify/src/mixins/registrable/index.ts
  3. VInput:https://github.com/vuetifyjs/vuetify/blob/v2.6.15/packages/vuetify/src/components/VInput/VInput.ts
  4. VInput 使用的可验证 mixin:https://github.com/vuetifyjs/vuetify/blob/v2.6.15/packages/vuetify/src/mixins/validatable/index.ts