Is it correct to use a v-model's value as the condition of an if-statement?

Viewed 109

How do I put the v-model="item.checked" as the condition of the if in below validations()?

<table>
    <tr v-for="(item, i) of $v.timesheet.items.$each.$iter" >
        <div>
            <td>
                <input 
                    type="checkbox" 
                    v-model="item.checked" 
                    v-on:click="disable(i)"
                />
            </td>
            <td>
                <input 
                    type="text" 
                    :id="'total_hour-' + i"
                />
            </td>
        </div>
    </tr>
    <tr>
        <div>
            <td>
                <button 
                    type="button" 
                    class="btn btn-sm btn-primary" 
                    @click="itemCount++"
                >Add Row
                </button>
            </td>
        </div>
    </tr>
</table>

<script>
    import { required, minLength } from "vuelidate/lib/validators";
    export default {
        data() {
            return {
                itemCount: 1,
                timesheet: { items: [{ total_hour: "", checked: false }] },
            }
        },
        methods: {            
            disable(index){
                const check = 
                        document.getElementById('total_hour-' + index).disabled
                $('#total_hour-' + index).attr('disabled', !check);
            }
        },
        watch: {
            itemCount(value, oldValue) {
                if (value > oldValue) {
                    for (let i = 0; i < value - oldValue; i++) {
                        this.timesheet.items.push({
                            total_hour: "",
                            checked: false,
                        })
                    }
                } else {
                    this.timesheet.items.splice(value);
                }
            }
        },
        validations() {
            if (  ?  ) {
                return {
                    timesheet: {
                        items: {
                            required,
                            minLength: minLength(1),
                            $each: { total_hour: {required} }
                        }
                    }
                }
            } else {
                return {
                    timesheet: {
                        items: {
                            required,
                            minLength: minLength(1),
                            $each: { total_hour: {} }
                        }
                    }
                }
            }
        }
    }
</script>
2 Answers

So as I understand, you want total_hour to be a required field only if checked is true. Vuelidate provides a nice built-in validator for this purpose called requiredIf. It is a contextified validator so you can reference a sibling property.

import { required, requiredIf, minLength } from 'vuelidate/lib/validators';

export default {
  ...
  validations: {
    timesheet: {
      items: {
        required,
        minLength: minLength(1),
        $each: {
          total_hour: {
            required: requiredIf('checked'),
          },
        },
      },
    },
  },
}

Another problem I see in your code is that you're trying to iterate over $v fields. $v fields are used to get validation states for your fields, you're not supposed to set $v fields. Using them as v-model for components will make vue set the $v fields. Try this:

<tr v-for="(item, i) in timesheet.items">

So, there are a few things to improve your code.

Replace watcher with a method

Watchers are pretty hard to debug and can cause side effects. They should be only used when really necessary. Instead, create a method, which adds a row:

addRow() {
  this.timesheet.items.push({
    total_hour: "",
    checked: false,
  })
}

For removing a row, do the same. Just create a method.

Create a component for each entry

By creating subComponents for timesheet items, you can handle validation easier and you can react on changes to individual entries better.

<table>
  <TimesheetItemRow
    v-for="(item) of $v.timesheet.items.$each.$iter"
    :item="item"
  />
  <tr>
    ...
  </tr>
</table>

To keep track of all the timesheet items in the parent component, you probably want to emit an event from the child component to the parent, containing the new entries data.

Don't use jQuery or JavaScript Code to manipulate DOM

Same as before, such things should be used only in super, super edge cases. One of the benefit of Frontend Frameworks like Vue.js is, that you don't need to do this.

Now, that you have a component for each entry, it's easy to handle disabling your input directly in the template

This is some (untested) code for the timesheet item component:

<template>
  <tr>
    <td>
      <input 
        type="checkbox" 
        value="item.checked
        @click="onClickCheckbox"
      />
    </td>

    <td>
      <input 
        type="text" 
        @input="onUpdateTotalHour"
        :disabled="!item.checked
      />
    </td>
  </tr>
</template>

<script>
  import { required } from "vuelidate/lib/validators";

  export default {
    props: {
      item: {
        type: Object
      }
    },

    methods: {
      onClickCheckbox (value) {
        this.$emit('on-click-checkbox', value)
      },

      onUpdateTotalHour (value) {
        this.$emit('on-update-total-hour', value)
      }
    },

    validations () {
      if (this.item.checked) {
        return {
          item: {
            total_hour: { required }
          }
        }
      }

      return {
        item: {
          total_hour: {}
        }
      }
    }
  }
</script>

The parent component needs to keep track of all the items, and needs to react on the emitted events.

Related