首页 > 解决方案 > VueJs - 表单提交时的 preventDefault()

问题描述

我需要以编程方式提交表单,但我也需要它preventDefault

现在我有以下内容:

submit() {
  this.$refs.form.submit()
}

它工作正常,但我无法阻止提交的默认设置,最终刷新页面。

标签: vue.jspreventdefault

解决方案


简短的回答

您可以将.prevent修饰符添加到(或您正在使用的@submit任何其他),如下所示:v-on

<form @submit.prevent="myMethod">
  <button type="submit"></button>
</form>

在提交表单的情况下,这将阻止刷新页面的默认行为。

长答案

有几种方法可以修改事件。

来自 Vue 3 文档

调用event.preventDefault()event.stopPropagation()内部事件处理程序是非常常见的需求。虽然我们可以在方法内部轻松地做到这一点,但如果方法可以纯粹是关于数据逻辑而不是处理 DOM 事件细节会更好。

为了解决这个问题,Vue 为 v-on 提供了事件修饰符。回想一下,修饰符是用点表示的指令后缀。

<!-- the click event's propagation will be stopped -->
<a @click.stop="doThis"></a>

<!-- the submit event will no longer reload the page -->
<form @submit.prevent="onSubmit"></form>

<!-- modifiers can be chained -->
<a @click.stop.prevent="doThat"></a>

<!-- just the modifier -->
<form @submit.prevent></form>

<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div @click.capture="doThis">...</div>

<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div @click.self="doThat">...</div>

另一种选择

有时我们还需要访问内联语句处理程序中的原始 DOM 事件。您可以使用特殊的 $event 变量将其传递给方法:

<button @click="warn('Form cannot be submitted yet.', $event)">
  Submit
</button>
// ...
methods: {
  warn: function (message, event) {
    // now we have access to the native event
    if (event) {
      event.preventDefault()
    }
    alert(message)
  }
}

干杯:)


推荐阅读