如何通过传递函数来创建表单验证规则?

How to create a form validation rule by passing a function?

我需要为表单域创建一个规则,允许我将该域的值与数组的各个元素进行比较。目前,我有这样的事情:

<template>
  <v-form v-model="valid" ref="form" >
          <v-text-field v-model="id" :rules="[...rules.required,...rules.repeatedID]"/>
  </v-form>
</template

<script>
import axios from 'axios';
export default {
  data() {    
    return{
       idQuestoes: [] //Array that gets populated from GET request
       rules: {
          required: [(v) => !!v || "Field is required"],
          repeatedID: [v => checkID(v) || "ID already exists"],
       }
   
  created() { 
    // Populating the array with values from database
    axios.get(`http://localhost:8001/question`)
      .then((response)=>{
        response.data.forEach((obj) =>{
          this.idQuestoes = obj.id
        });
      },(error) =>{
          console.log(error);
    });
 
   methods: {

    checkID(item){
      this.idQuestoes.forEach((value) =>{
        if(value == item){
          return false
        }
      }) 
    }
   }

</script>

大部分代码只是用来自数据库的值填充数组,这些值只是字符串。我现在 运行 遇到的问题是它说 checkID 未定义。

我能解决问题吗?还是这个解决方案根本行不通?我对其他想法持开放态度,以使此表单验证规则起作用。

另外,如果我遗漏了一些代码来确保一切正常,那是因为已经有很多代码了,所以我试图将它保持在最低限度。

要使用组件方法,方法名需要加上前缀this.:

repeatedID: [v => this.checkID(v) || "ID already exists"],
                    

此外,checkID() 应该使用 Array.prototype.find() 来搜索数组中的现有 ID:

export default {
  methods: {
    checkID(item) {
      return !this.idQuestoes.find(x => x === item)
    },
  },
}

此外,axios 回调应该使用 Array.prototype.push()obj.id 附加到 idQuestoes[],或使用 Array.prototype.map() 映射 API 响应到 ids:

axios.get(`http://localhost:8001/question`)
  .then((response)=> {

    response.data.forEach((obj) =>{
      //this.idQuestoes = obj.id ❌

      this.idQuestoes.push(obj.id) ✅
    });

    // OR
    this.idQuestoes = response.data.map(x => x.id)
  })

demo