Home > Net >  Vue 3 Composition API - Disabling form submit button until all conditions are met
Vue 3 Composition API - Disabling form submit button until all conditions are met

Time:05-17

I want to disable my form submit button until all the input fields are filled in and there are no errors.

<button
  :disabled="disabled"
  type="submit"
  value="Submit"
  >
  Suggest
</button>

let disabled = ref(true);
let error = ref(false);

nextTick(() => {
  let inputs = Array.from(document.getElementsByClassName("form__input"));
  if (!error.value) {
    inputs.forEach((input) => {
      if (input.value === "") {
        disabled.value = true;
      } else {
        disabled.value = false;
      }
    });
  }
})

The button is disabled by default but it won't 'enable' itself once the already mentioned conditions are met.

So far, I'm using a helper lifecycle hook nextTick() which clearly doesn't help me in this situation.

The 'disabled' state will update in the console but not on the DOM.

How can I approach this?

Cheers

CodePudding user response:

maybe you should use v-model,computed or @input to listen event and change button disable status.

CodePudding user response:

The easiest solution is by using a computed value to set the disabled state of the button - based on the input values - if any are empty, button is disabled

Here's a basic example

const { ref, createApp, computed } = Vue;
createApp({
    setup() {
        const input1 = ref("");
        const input2 = ref("");
        const input3 = ref("");
        // disabled is true if ANY input is empty string
        const disabled = computed(() => !input1.value || !input2.value || !input3.value);
        const clicked = () => console.log('clicked');
        return { input1, input2, input3, disabled, clicked };
    }
}).mount('#app');
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  Input 1: <input v-model="input1" type="text"/><br/>
  Input 2: <input v-model="input2" type="text"/><br/>
  Input 3: <input v-model="input3" type="text"/><br/>
  <button :disabled="disabled" @click="clicked">Click me</button>
</div>

  • Related