search

Home  >  Q&A  >  body text

Vue 3 Composition API - Disable form submit button until all conditions are met

I want to disable the form submit button until all 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 will not "enable" itself once the conditions already mentioned are met.

So far I'm using a secondary lifecycle hook nextTick() which obviously doesn't help me in this case.

The "disabled" status will be updated in the console, but not on the DOM.

How can I solve this problem?

cheers

P粉360266095P粉360266095404 days ago1085

reply all(3)I'll reply

  • P粉180844619

    P粉1808446192023-11-14 00:30:04

    Maybe you should use v-model, compulated or @input to listen to events and change the button disabled state.

    reply
    0
  • P粉828463673

    P粉8284636732023-11-14 00:15:17

    The simplest solution is to set the disabled state of the button using a calculated value - based on the input value - if any are empty, the button is disabled

    This is 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');
    sssccc
    
    Input 1:
    Input 2:
    Input 3:

    reply
    0
  • 尊渡假赌尊渡假赌尊渡假赌

    尊渡假赌尊渡假赌尊渡假赌2023-11-20 15:25:48

    . . . . test

    reply
    0
  • Cancelreply