You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel/VueJS多提交按钮表单:SweetAlert确认后无法提交求助

解决Laravel/Vue项目中SweetAlert确认后表单无法提交的问题

问题核心原因

  1. 全局event变量不可靠:直接使用event.preventDefault(),在Vue方法中全局event可能无法正确获取,需通过事件参数传递。
  2. jQuery DOM操作不符合Vue规范:用$('input[name="submit"]').closest("form")获取表单易出现选择错误,Vue推荐用ref操作DOM元素。
  3. 表单提交触发逻辑问题:直接调用form.submit()时,若表单绑定了Vue的submit事件,可能无法触发对应处理逻辑。

修正后的代码示例

模板部分(添加表单ref,传递事件参数)

<template>
  <form ref="submitForm">
    <div class="large-12 medium-12 small-12 cell">
      <input type="submit" name="submit" @click="showAlertConfirm($event)">
    </div>
  </form>
</template>

脚本部分(用Vue refs获取表单,修正事件处理)

<script>
export default {
  methods: {
    showAlertConfirm(event) {
      // 阻止默认提交行为
      event.preventDefault();
      // 通过Vue ref获取表单元素
      const form = this.$refs.submitForm;

      this.$swal.fire({
        title: '确定要提交吗?',
        text: "提交后无法撤销此操作!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认提交'
      }).then((result) => {
        if (result.isConfirmed) {
          // 提交表单
          form.submit();
          this.$swal.fire(
            '提交成功!',
            '你的文件已提交。',
            'success'
          )
        }
      })
    }
  }
}
</script>

额外优化建议

  • 若表单使用Vue的v-model和@submit事件处理,建议确认后调用对应提交方法而非直接操作DOM:
    // 假设存在handleSubmit方法处理表单提交逻辑
    if (result.isConfirmed) {
      this.handleSubmit();
      this.$swal.fire('提交成功!', '你的文件已提交。', 'success')
    }
    
  • 尽量减少Vue项目中jQuery的使用,用Vue内置API操作DOM和数据,降低代码耦合度。

内容的提问来源于stack exchange,提问作者kritika555

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:45:30