Vue 3 Composition API - Disable form submit button until all conditions are met
P粉360266095
P粉360266095 2023-11-13 09:41:53
0
3
1165

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粉360266095
P粉360266095

reply all(3)
P粉180844619

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

P粉828463673

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:
尊渡假赌尊渡假赌尊渡假赌

. . . . test

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template