首页  >  问答  >  正文

Vue 3 Composition API - 禁用表单提交按钮,直到满足所有条件

我想禁用表单提交按钮,直到所有输入字段均已填写并且没有错误。

<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;
      }
    });
  }
})

该按钮默认处于禁用状态,但一旦满足已经提到的条件,它就不会自行“启用”。

到目前为止,我正在使用辅助生命周期挂钩 nextTick() ,这显然在这种情况下对我没有帮助。

“禁用”状态将在控制台中更新,但不会在 DOM 上更新。

我该如何解决这个问题?

干杯

P粉360266095P粉360266095311 天前970

全部回复(3)我来回复

  • P粉180844619

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

    也许您应该使用v-modelcompulated@input来监听事件并更改按钮禁用状态。

    回复
    0
  • P粉828463673

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

    最简单的解决方案是使用计算值来设置按钮的禁用状态 - 基于输入值 - 如果有任何为空,则按钮被禁用

    这是一个基本示例

    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:

    回复
    0
  • 尊渡假赌尊渡假赌尊渡假赌

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

    。。。。测试

    回复
    0
  • 取消回复