Search code examples
formsvue.jsvalidationvuejs2ref

validating forms $refs returning undefined vuejs


I am trying to validate my form but when I try to call the validation method it's returning the value undefined instead of Boolean. Can anyone help me fix the problem ? This below code is the one I am using to validate. By the way I am trying validate it in a child component. Which is only gonna render and show a dialogue when clicking a button.

   computed:{
        employeeFormValidation(){
          this.$refs.employeeForm.validate((valid)=>{
            return valid ? true : false
        },
        employeeAddressValidation(){
          this.$refs.employeeAddress.validate((valid)=>{
            return valid ? true : false
          })
        },
        employeeDetailsValidation(){
          this.$refs.employeeDetails.validate((valid)=>{
            return valid ? true : false
          })
        },
        bankDetailsValidation(){
          this.$refs.bankDetails.validate((valid)=>{
            return valid ? true : false
        })
        },

Solution

  • Vue is not design as everything is reactive, the docs says "$refs is also non-reactive"

    One way to do is use methods instead of computed, But the downside is that this will be re-called even if the dependency has not changed.

    However, according to Vue's design philosophy, it should use less refs, accept the values emited by the component, and store them in data.

    <your-child-components
       @validate="(ok) => (valiateEmployeeDetails = ok)"
    >
    <your-child-components
       @validate="(ok) => (valiateEmployeeAddress = ok)"
    >
    
    {
      data(){
        return {
          valiateEmployeeDetails: false,
          valiateEmployeeAddress: false,
        }
      }
    }
    

    React has a doucment about "when to use refs", it's the same in Vue.